c语言编程杀死指定进程,将C程序中的stdin重定向到另一个进程

我有一个C程序,我想让它用tr过滤所有输入.所以,我想启动tr作为子进程,将我的stdin重定向到它,然后捕获tr的stdout并从中读取.

编辑:这是我到目前为止的代码,它不起作用.它立即发生了段错误,但我不明白为什么:

#include

#include

int main(int argc, char** argv){

int ch;

int fd = stripNewlines();

while((ch = getc(fd)) != EOF){

putc(ch, stdout);

}

return 0;

}

int stripNewlines(){

int fd[2], ch;

pipe(fd);

if(!fork()){

close(fd[0]);

while((ch = getc(stdin)) != EOF){

if(ch == '\n'){ continue; }

putc(ch, fd[1]);

}

exit(0);

}else{

close(fd[1]);

return fd[0];

}

}

编辑:原来这是两件事:一个是我的标题没有将stdin和stdout定义为0和1,所以我实际上正在读/写完全随机的管道.另一个原因是由于某种原因,getc和putc不能正常工作,所以我不得不使用read()和write().如果我这样做,它是完美的:

#include

#include

int main(int argc, char** argv){

int ch;

int fd = stripNewlines();

while(read(fd, &ch, 1) == 1){

write(1, &ch, 1);

}

return 0;

}

int stripNewlines(){

int fd[2];

int ch;

pipe(fd);

if(!fork()){

close(fd[0]);

while(read(0, &ch, 1) == 1){

if(ch == '\n'){ continue; }

write(fd[1], &ch, 1);

}

exit(0);

}else{

close(fd[1]);

return fd[0];

}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值