c语言system到子进程,如何在c中使用system()命令执行进程的pid

简单回答:你做不到.

system()的目的是阻止何时执行命令.

但你可以像这样“欺骗”:

pid_t system2(const char * command, int * infp, int * outfp)

{

int p_stdin[2];

int p_stdout[2];

pid_t pid;

if (pipe(p_stdin) == -1)

return -1;

if (pipe(p_stdout) == -1) {

close(p_stdin[0]);

close(p_stdin[1]);

return -1;

}

pid = fork();

if (pid < 0) {

close(p_stdin[0]);

close(p_stdin[1]);

close(p_stdout[0]);

close(p_stdout[1]);

return pid;

} else if (pid == 0) {

close(p_stdin[1]);

dup2(p_stdin[0], 0);

close(p_stdout[0]);

dup2(p_stdout[1], 1);

dup2(::open("/dev/null", O_RDONLY), 2);

/// Close all other descriptors for the safety sake.

for (int i = 3; i < 4096; ++i)

::close(i);

setsid();

execl("/bin/sh", "sh", "-c", command, NULL);

_exit(1);

}

close(p_stdin[0]);

close(p_stdout[1]);

if (infp == NULL) {

close(p_stdin[1]);

} else {

*infp = p_stdin[1];

}

if (outfp == NULL) {

close(p_stdout[0]);

} else {

*outfp = p_stdout[0];

}

return pid;

}

在这里,您不仅可以拥有流程的PID,还可以拥有STDIN和STDOUT.玩得开心!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值