定为java进程挂起原因_为什么在这里使用进程替换会导致挂起?

我有一个程序,需要启动其他程序,可能用文件和管道替换其stdio。尽管子进程确实从源管道获取了它的I / O,但似乎“起作用”,但是不幸的是,这也导致了挂起。子进程似乎从未获得EOF。

这里是代码的最小复制,为什么在打印"Hello World\n"后仍然挂起?

#include

#include

#include

#include

#include

#include

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

switch (pid_t pid = fork()) {

case 0: {

// in child

// replace the child's stdin with whatever filename is given as argv[1]

freopen(argv[1], "r+b", stdin);

// construct an argv array for to exec, no need for anything except

// argv[0] since we want it to use stdin

char path[] = "/bin/cat";

char *args[] = {path, NULL};

// run it!

execv(args[0], args);

abort(); // we should never get here!

}

case -1:

// error

return -1;

default: {

// in parent, just wait for the sub-process to terminate

int status;

const auto r = waitpid(pid, &status, __WALL);

if (r == -1) {

perror("waitpid");

return -1;

}

break;

}

}

}

# runs printf creating a pipe, which is this passed as the argv of my test program

./test >(printf "Hello\n")

0

投票

./test

切换到>(...)至

freopen(argv[1], "rb", stdin);

请勿使用r+。您只从文件中读取,因此将其设为r。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值