linux IPC的PIPE

一、PIPE(无名管道)

函数原型:

#include <unistd.h>

int pipe(int fd[2]);

通常,进程会先调用pipe,接着调用fork,从而创建从父进程到子进程的IPC通道。

父进程和子进程之间也可用通过pipe通信。

例子,父进程到子进程hello world:

 1 #include "apue.h"
 2 
 3 int main(void)
 4 {
 5         int n;
 6         int fd[2];
 7         pid_t pid;
 8         char line[MAXLINE];
 9 
10         if(pipe(fd) < 0)
11                 err_sys("pipe error");
12         if((pid = fork()) < 0) {
13                 err_sys("fork error");
14         } else if (pid > 0) {
15                 close(fd[0]);
16                 write(fd[1], "hello world\n", 12);
17         } else {
18                close(fd[1]);
19               n = read(fd[0], line, MAXLINE);
20                write(STDOUT_FILENO, line, n);
21         }
22         exit(0);
23 }

 

二、函数popen和pclose

#include <stdio.h>

FILE *open(const char *cmdstring, const char *type);

int pclose(FILE *fp);

创建一个管道,fork一个子进程,关闭未使用的管道端,执行一个shell运行命令,然后等待命令终止。

#include "apue.h"
#include <stdio.h>

int main()
{
    FILE *fp;
    char ch, line[300];

    fp = popen("ls *.c", "r");
    if(fp != NULL)
    {
        while(fgets(line, 300, fp))
        {
            printf("line=%s\n", line);
        }
    }

    pclose(fp);

    return 0;
}

 

转载于:https://www.cnblogs.com/ch122633/p/8058671.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值