//pipe3.c
//在子进程中运行一个与其父进程完全不同的另外一个程序:利用exec调用
//使用两个程序:
//1.数据生产者,用来创建管道和启动子进程pipe3.c
//2.数据消费者,pipe4.c
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <pthread.h>
int main()
{
int data_processed;
int file_pipes[2];
const char some_data[] = "123";
char buffer[BUFSIZ + 1];
pid_t fork_result;
memset(buffer, '\0', sizeof(buffer));
if (pipe(file_pipes) == 0)
{
fork_result = fork();
if (fork_result == (pid_t)-1)
{
fprintf(stderr, "Fork failure");
exit(EXIT_FAILURE);
}
if (fork_result == 0) //子进程
{
//把读取管道数据的文件描述符保存到一个缓存区,该缓冲区中的内容构成pipe4程序的一个参数
sprintf(buffer, "%d", file_pipes[0]); //Write formatted data to string
(void)execl("pipe4", "pipe4", buffer, (char *)0); //执行pipe4程序,pipe4,buffer为参数
exit(EXIT_FAILURE);
}
else //输出子进程中写入的什么数据shenmeshuju
{
data_processed = write(file_pipes[1], some_data,
strlen(some_data));
printf("%d - wrote %d bytes\n", getpid(), data_processed);
}
}
exit(EXIT_SUCCESS);
}
//pipe4.c
//数据消费者程序,负责读取数据
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[]) //参数:pipe4,buffer
{
int data_processed;
char buffer[BUFSIZ + 1];
int file_descriptor;
memset(buffer, '\0', sizeof(buffer));
sscanf(argv[1], "%d", &file_descriptor); //Read formatted data from string
data_processed = read(file_descriptor, buffer, BUFSIZ);
printf("%d - read %d bytes: %s \n", getpid(), data_processed, buffer);
exit(EXIT_SUCCESS);
}