直白来说就是子进程直接在新的程序中运行!
a.功能实现:
有程序P1, P2
使用管道进行通信
P1由用户输入一个字符串,然后把该字符串发给p2
P2接收到以后,把该字符串打印出来
b 难点:子进程使用exec启动新程序运行后,
新进程能够使用原来子进程的管道(因为exec能共享原来的文件描述符)
但问题是新进程并不知道原来的文件描述符是多少!
解决方案:
把子进程中的管道文件描述符,用exec的参数传递给新进程。
p1:
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(void)
{
int fd[2];
int ret;
char buff1[1024];
char buff2[1024];
pid_t pd;
ret = pipe(fd);
if (ret !=0) {
printf("create pipe failed!\n");
exit(1);
}
pd = fork();
if (pd == -1) {
printf("fork error!\n");
exit(1);
} else if (pd == 0) {
//bzero(buff2, sizeof(buff2));
sprintf(buff2, "%d", fd[0]);
execl("main3_2", "main3_2", buff2, 0);
printf("execl error!\n");
exit(1);
} else {
strcpy(buff1, "Hello!");
write(fd[1], buff1, strlen(buff1));
printf("process(%d) send information:%s\n", getpid(), buff1);
}
if (pd > 0) {
wait();
}
return 0;
}
p2:
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(int argc, char* argv[])
{
int fd;
char buff[1024] = {0,};
sscanf(argv[1], "%d", &fd);
read(fd, buff, sizeof(buff));
printf("Process(%d) received information:%s\n", getpid(), buff);
return 0;
}