gpt4 book ai didi

c - Shell 提示符在子进程通过 putty 完成之前返回

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:45:22 26 4
gpt4 key购买 nike

请查看以下代码示例:

int main() {
pid_t childpid;
char buf[100] = {0};

if((childpid = fork()) == -1)
{
perror("fork");
exit(1);
}

if(childpid == 0) {
sprintf(buf,"child process id: %d\n",getpid());
write(1,buf,strlen(buf));
}
else {
sprintf(buf,"parent process id: %d\n",getpid());
write(1,buf,strlen(buf));
// fix here
wait(&childpid);
}
return 0;

直接在 Linux 机器的终端上运行时,输出符合预期:

[user@192 ~]$ ./test 
parent process id: 28788
child process id: 28789

另一方面,通过 Putty 运行同样的操作会带来:

parent process id: 28978
[user@192 ~]$ child process id: 28979

谢谢大家的建议。添加等待调用会在 child 完成后提示。

我希望在同一个问题中考虑输出也不同但独立于 wait() 调用的另一种情况是个好主意。

这是 dup() 调用实现:

int main() {
pid_t childpid;
char string[] = "c\nb\na";

if((childpid = fork()) == -1)
{
perror("fork");
exit(1);
}

if(childpid == 0) {
close(0); // close STDIN
close(fd[1]); // close write end of a pipe
dup(*fd); // duplicate read end of the pipe to STDIN
execlp("sort","sort",NULL); // run sort(1) command
}
else {
close(*fd); // close read end of a pipe
write(fd[1],string,strlen(string));
}
return 0;

再次不同的输出,直接从终端运行程序,给出:

[user@192 pipe]$ ./dup
a
b
c
[user@192 pipe]$

并通过腻子连接:

root@debian-512mb-ams2-01:~/C/inner/pipe# a  
b
c

在第二个例子中提示永不回来:(

它可以是什么?)

最佳答案

您需要wait()对于子进程:

if(childpid == 0) {
sprintf(buf,"child process id: %d\n",getpid());
write(1,buf,sizeof(buf));
}
else {
sprintf(buf,"parent process id: %d\n",getpid());
write(1,buf,sizeof(buf));
wait(childpid); // <---
}
return 0;

关于c - Shell 提示符在子进程通过 putty 完成之前返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47569627/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com