linux程序设计--在子进程中运行一个与其父进程完全不同的另外一个程序

//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);
}

 

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值