- 论坛徽章:
- 13
|
代码如下:- #include <apue.h>
- #include <sys/wait.h>
- #include <unistd.h>
- #include <limits.h>
- #include <fcntl.h>
- #define READ_FD 0
- #define WRITE_FD 1
- #define RD_CHUNK 10
- #define ATOMIC
- #ifndef PIPE_BUF
- #define PIPE_BUF _POSIX_PIPE_BUF
- #endif
- void do_nothing(int signo)
- {
- return ;
- }
- int main(int argc, char *argv[])
- {
- int i,repeat;
- int bytesread;
- int mssglen;
- pid_t child1, child2;
- int fd[2];
- int outfd;
- char message[RD_CHUNK + 1];
- char *Child1_Chunk, *Child2_Chunk;
- long Chunk_Size;
- static struct sigaction sigact;
- sigact.sa_handler=do_nothing;
- sigfillset(&(sigact.sa_mask));
- sigaction(SIGUSR1, &sigact, NULL);
- //check argc
- if( argc < 2){
- fprintf(stderr,"Usage: %s size \n",argv[0]);
- exit(1);
- }
- //try to create pipe
- if(-1 == pipe(fd)){
- perror("pipe call");
- exit(2);
- }
- repeat=atoi(argv[1]);
- #ifdef ATOMIC
- Chunk_Size = PIPE_BUF;
- #else
- Chunk_Size = PIPE_BUF + 200;
- #endif
- printf("Chunk size =%ld\n",Chunk_Size);
- printf("Value of PIPE_BUF is %ld\n",PIPE_BUF);
- Child1_Chunk=calloc(Chunk_Size,sizeof(char));
- Child2_Chunk=calloc(Chunk_Size,sizeof(char));
- if((NULL == Child1_Chunk) ||(NULL == Child2_Chunk)){
- perror("calloc");
- exit(2);
- }
- //create the string that child1 writes
- Child1_Chunk[0] = '\0'; //just to be safe
- for(i=0; i < Chunk_Size -2; i++)
- strcat(Child1_Chunk,"X");
- strcat(Child1_Chunk,"\n");
- //create the string that child2 writes
- Child2_Chunk[0]='\0'; //just to be safe
- for(i=0;i<Chunk_Size -2;i++)
- strcat(Child2_Chunk,"y");
- strcat(Child2_Chunk,"\n");
- //create first child process
- switch(child1 = fork()){
- case -1: //fork failed -- exit
- perror("fork()");
- exit(3);
- case 0: //child1 code
- mssglen=strlen(Child1_Chunk);
- pause();
- sleep(5);
- for(i=0;i<repeat;i++){
- if(write(fd[WRITE_FD],Child1_Chunk,mssglen)!= mssglen){
- perror("write");
- exit(4);
- }
- }
- close(fd[WRITE_FD]);
- exit(0);
- default: //parent creates second child process
- switch(child2 = fork()){
- case -1: //fork failed --exit
- perror("fork()");
- exit(5);
- case 0: //child2 code
- mssglen=strlen(Child2_Chunk);
- pause();
- for(i=0;i<repeat;i++){
- if(write(fd[WRITE_FD],Child2_Chunk,mssglen)!= mssglen){
- perror("write");
- exit(6);
- }
- }
- close(fd[WRITE_FD]);
- exit(0);
- default: //parent code
- outfd=open("pd2_output",O_WRONLY|O_CREAT|O_TRUNC,0644);
- if(-1==outfd){
- perror("open");
- exit(7);
- }
- close(fd[WRITE_FD]);
- kill(child2,SIGUSR2);
- kill(child1,SIGUSR1);
- while((bytesread = read(fd[READ_FD],message,RD_CHUNK))!=0)
- if(bytesread >0 ){ //more data
- write(outfd,message,bytesread);
- }
- else{
- perror("read() ");
- exit(8);
- }
- close(outfd);
- //collect zombies
- for(i=1;i<=2;i++)
- if(wait(NULL)==-1){
- perror("wait failed");
- exit(9);
- }
- close(fd[READ_FD]);
- free(Child1_Chunk);
- free(Child2_Chunk);
- }
- exit(0);
- }
- }
复制代码 我看过pd2_output,里面全是X,没有y,也就是说child2 从来没有机会跑过。
为什么呢? |
|