gpt4 book ai didi

c - shell 作业控制

转载 作者:行者123 更新时间:2023-12-04 10:45:26 25 4
gpt4 key购买 nike

对于我的学校项目,我正在实现一个 shell,我需要工作控制方面的帮助。
如果我们输入命令,请说 cat & ,然后因为 &它应该在后台运行,但它不起作用。我有这个代码:

{
int pid;
int status;
pid = fork();
if (pid == 0) {
fprintf(stderr, "Child Job pid = %d\n", getpid());
execvp(arg1, arg2);
}
pid=getpid();
fprintf(stderr, "Child Job pid is = %d\n", getpid());
waitpid(pid, &status, 0);
}

最佳答案

您应该为 SIGCHLD 信号设置一个信号处理程序,而不是直接等待。每当子进程停止或终止时,都会发送 SIGCHLD。查看 process completion 的 GNU 描述.

本文末尾有一个示例处理程序(我或多或少地复制并粘贴在下面)。尝试从中建模您的代码。

 void sigchld_handler (int signum) {
int pid, status, serrno;
serrno = errno;
while (1) {
pid = waitpid(WAIT_ANY, &status, WNOHANG);
if (pid < 0) {
perror("waitpid");
break;
}
if (pid == 0)
break;
/* customize here.
notice_termination is in this case some function you would provide
that would report back to your shell.
*/
notice_termination (pid, status);
}
errno = serrno;
}

关于这个主题的另一个很好的信息来源是 Advanced Programming in the UNIX Environment ,第 8 章和第 10 章。

关于c - shell 作业控制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13328402/

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