linux管道子进程,在linux中使用管道使用父进程和子进程

我想用C实现这个linux命令。切-b 1在linux中使用管道使用父进程和子进程

我试图做到这一点是

调用的ls -l的父进程 将LS的输出-l以文件的方式(写入文件)

呼吁削减子进程 读取文件(一个写入父进程) 实行切削到文件 打印输出

这是远远我所做的

/* pipe.c */

#include

#include

#include

#include

#include

void main()

{

int filedes[2];

int p;

pid_t pid, pid1;

p=pipe(filedes);

FILE *stream;

char buff[20];

printf("pipe command returns %d, %d ,%d\n",p, filedes[0],filedes[1]);

if(pipe(filedes) == -1) /* Create the pipe */

printf("error pipe");

pid1=fork();

pid=getpid();

switch (pid1) { /* Create a child process */

case -1:

printf("error fork");

case 0: /* Child */

/* Close unused write end */

/* Child can now read from pipe */

if (close(filedes[1]) == -1)

printf("error close");

printf("I am a child process pid %d, and will read from pipe\n",pid);

while (read(filedes[0], &buff, 1) > 0)

write(STDOUT_FILENO, &buff, 1);

write(STDOUT_FILENO, "\n", 1);

close(filedes[0]);

_exit(EXIT_SUCCESS);

break;

default: /* Parent */

/* Close unused read end */

/* Parent can now write to pipe */

if (close(filedes[0]) == -1)

printf("error close");

printf("I am the parent process pid %d, and will write to pipe\n", pid);

stream = fdopen(filedes[1], "w");

strcpy(buff, "This is a test\n");

write(filedes[1], buff, strlen(buff));

char *args[80];

args[0] = "ls";

args[1] = "-l";

args[2] = NULL;

execvp(args[0],args);

int bak, new;

bak = dup(1);

new = open("/home/urwa/abc.txt", O_WRONLY);

dup2(new, 1);

close(new);

close(filedes[1]); /* Reader will see EOF */

wait(NULL); /* Wait for child */

exit(EXIT_SUCCESS);

break;

}

}

这段代码工作得很好。并在展台上打印输出测试语句。以及ls -l输出。但该文件是空的。我究竟做错了什么。 我也试过freopen如下..仍然是空文件。 :/

FILE *fp;

fp = freopen ("/temp/abc.txt", "a+", stdout);

2013-05-06

urwaCFC

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值