二十一. 复习
二十二. 父子进程间使用文件进行通信
这里的重点,在于理解,fork完了之后,父进程里的文件描述符,也会做相应的复制。比如父进程的3号文件描述符指向temp这个文件,那么子进程的3号文件描述符,也会指向temp这个文件
process_file.c
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <fcntl.h>
// 操作终端文件 /dev/tty默认阻塞
int main(int argc, const char* argv[])
{
int fd = open("temp", O_CREAT | O_RDWR, 0664);
if(fd == -1)
{
perror("open error");
exit(1);
}
pid_t pid = fork();
if(pid == -1)
{
perror("fork error");
exit(1);
}
if(pid > 0)
{
char* p = "近期,微软向Linux开发人员伸出了橄榄枝,希望Linux开发人员能够转移到Windows 10平台上进行开发。";
write(fd, p, strlen(p)+1);
close(fd);
}
else if(pid == 0)
{
// 睡1s保证父进程已经完成了文件的写操作
sleep(1);
char buf[1024];
lseek(fd, 0, SEEK_SET);
int len = read(fd, buf, sizeof(buf));
printf("%s\n", buf);
close(fd);
}
return 0;
}
二十三. 文件
multi_process.c
#include <stdio.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
int main(int argc, const char* argv[])
{
int num = 3;
int i = 0;
pid_t pid;
for(i=0; i<num; ++i)
{
pid = fork();
if(pid == 0)
{
break;
}
}
if(i == 0)
{
execlp("ps", "ps", "aux", NULL);
perror("execlp ps");
exit(1);
}
else if(i == 1)
{
execl("/home/kevin/test/app", "app", NULL);
perror("execl app");
exit(1);
}
else if(i == 2)
{
execl("./error", "error", NULL);
perror("execl error");
exit(1);
}
else if(i == num)
{
// 回收
int status;
pid_t wpid;
//下一行,与这一行的写法等价 while( (wpid = wait(&status)) != -1 )
while( (wpid = waitpid(-1, &status, WNOHANG)) != -1 )
{
printf(" ----- child died pid = %d\n", wpid);
if(WIFEXITED(status))
{
printf("return value %d\n", WEXITSTATUS(status));
}
else if(WIFSIGNALED(status))
{
printf("died by signal: %d\n", WTERMSIG(status));
}
}
}
return 0;
}
二十四. waitpid函数
以下图里,A本来有1,2,3,4共四个子进程。然后我们把A的4号进程,送给了B进程。在这样的情况下。函数waitpid中如果pid==0,那么并不能影响到B中的4号进程,因为并不在同一个组里了。
二十五. IPC的概念