intmain(void) { int fd[2]; char buf[BUFSIZE] = "hello my child!\n"; pid_t pid; int len;
// create a pipe if((pipe(fd)) < 0) err_quit("pipe failed\n");
// create a son process pid = fork(); if(pid<0) err_quit("fork failed\n"); // parent process do this elseif(pid>0) { close(fd[0]);// father process close read port (fd[0]) write(fd[1], buf, strlen(buf));// write to pipe printf("I am parent process(ID:%d),write pipe ok\n", getpid()); exit(0); } // son process do this else//(pid == 0) { close(fd[1]);// son process close itself write port (fd[1]) len = read(fd[0], buf, BUFSIZE);// read from pipe if(len<0) err_quit("process failed when read a pipe\n"); else { printf("I am son process(ID:%d),read pipe ok\n", getpid()); write(STDOUT_FILENO, buf, len); } exit(0); }
}
编译后执行:
1 2 3 4
$ ./parent_pipe_child I am parent process(ID:4953),write pipe ok I am son process(ID:4954),read pipe ok hello my child!
// create the son process1 pid = fork(); if(pid < 0) err_quit("fork failed\n"); elseif(pid == 0)// son process1 { close(fd[0]);// close read port write(fd[1], buf, strlen(buf));// write printf("I am son process1(ID:%d), write pipe ok\n", getpid()); exit(0); }
// create the son process2 pid = fork(); if(pid < 0) err_quit("fork failed\n"); elseif(pid > 0) { close(fd[0]);// close read port close(fd[1]);// close write port printf("I am parent process(ID:%d), close my pipe\n", getpid()); exit(0); } else { close(fd[1]);// close write port len = read(fd[0], buf, BUFSIZE);// read printf("I am son process2(ID:%d), read pipe ok\n", getpid()); write(STDOUT_FILENO, buf, len); exit(0); }
return0; }
编译后执行:
1 2 3 4 5
$ ./brother_pipe I am parent process(ID:4962), close my pipe I am son process1(ID:4963), write pipe ok I am son process2(ID:4964), read pipe ok hello my brother!
#include<unistd.h> #include<stdio.h> intmain() { pid_t fpid; //fpid表示fork函数返回的值 int count=0;
fpid=fork(); if (fpid < 0) printf("error in fork!"); // son process see fpid as 0 elseif (fpid == 0) { printf("I am the child process, my process id:%d\n",getpid()); count++; } // parent process see fpid as a non 0 num else// (fpid > 0) { printf("I am the parent process, my process id: %d\n",getpid()); count++; }
printf("统计结果是: %d\n",count); return0; }
运行结果:
1 2 3 4 5
./forktest I am the parent process, my process id: 5892 统计结果是: 1 I am the child process, my process id:5893 统计结果是: 1