1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
|
#include "Pipe.h"
#include <pthread.h>
#include <sys/signal.h>
#include <unistd.h>
#include <sys/types.h>
#include <iostream>
#define READ 0
#define WRITE 1
pid_t popen2(const char *command, int *infp, int *outfp)
{
int p_stdin[2], p_stdout[2];
pid_t pid;
if (pipe(p_stdin) != 0 || pipe(p_stdout) != 0)
return -1;
pid = fork();
if (pid < 0)
return pid;
else if (pid == 0)
{
close(p_stdin[WRITE]);
dup2(p_stdin[READ], READ);
close(p_stdout[READ]);
dup2(p_stdout[WRITE], WRITE);
execl("/bin/sh", "sh", "-c", command, NULL);
perror("execl");
exit(1);
}
if (infp == NULL)
close(p_stdin[WRITE]);
else
*infp = p_stdin[WRITE];
if (outfp == NULL)
close(p_stdout[READ]);
else
*outfp = p_stdout[READ];
return pid;
}
void *readFromPipe( void *ptr )
{
char buffer[1024];
memset(buffer, '\0', sizeof(buffer));
int fd_in1 =0;
int fd_out1;
pid_t pid1 = popen2("../MyBonjourClient/build/dns-sd -L Franz _http._tcp", &fd_in1, &fd_out1);
if(pid1 <= 0)
{
printf("Unable to exec prog");
}
bool bCopy=false;
bool bEnd=false;
int iNumberChar=0;
while(!bEnd) //read process output
{
char c1;
if(read(fd_out1, &c1, 1) <= 0)
{
break; //no data
}
else
{
if(bCopy)
{
buffer[iNumberChar]=c1;
iNumberChar++;
}
if(c1=='\n')
{
if(bCopy==true)
{
// beende Kind
bEnd=true;
}
bCopy=true;
}
printf("%c",c1);
}
}
kill(pid1,SIGINT);
//GM: signal senden thread end success
pthread_exit((void*)EXIT_SUCCESS);
//GM: signal senden thread end error
//pthread_exit((void*)EXIT_FAILURE);
}
///////////////////////////////////////////////////////////////////////////////
int main(int argc, char **argv)
{
pthread_t thread1;
int iret1;
/* Create independent threads each of which will execute function */
iret1 = pthread_create( &thread1, NULL, readFromPipe, NULL);
/* Wait till threads are complete before main continues. Unless we */
/* wait we run the risk of executing an exit which will terminate */
/* the process and all threads before the threads have completed. */
//pthread_join( thread1, NULL);
// GM: soll man den Thread detached machen? Dann ist er nicht mehr joinable S.339
//pthread_detach(thread1);
//GM: Beenden eines Thread
//sleep(10);
//int iErr = pthread_kill(thread1,SIGQUIT);
//printf("Error: %d\n",iErr);
while(1)
{
//printf("main\n");
sleep(1);
}
printf("Thread 1 returns: %d\n",iret1);
exit(EXIT_SUCCESS);
}
//////////////////////////////////////////////////////////////////////////////
|