我正在学习 C 并尝试执行以下程序。
过去,我使用过 fork() 和 exec(),但用于相当简单的应用程序。
但是,程序应该执行以下操作:
1.程序必须使用Fork()和Exec()
2. 必须调用多个程序,一次一个
3. 必须杀掉之前的程序,一次只能运行一个程序
4. 程序必须运行到 ctrl-c
已执行
上一个示例 fork()
& exec()
代码。如何修改以下代码来实现上述步骤?
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
int main(int argc, char **argv)
{
void runit(void);
int pid; /* process ID */
switch (pid = fork())
{
case 0: /* a fork returns 0 to the child */
runit();
break;
default: /* a fork returns a pid to the parent */
sleep(5); /* sleep for 5 seconds */
printf("I'm still here!\n");
break;
case -1: /* something went wrong */
perror("fork");
exit(1);
}
exit(0);
}
void runit(void)
{
printf("About to run ls\n");
execlp("ls", "ls", "-af", "/", (char*)0);
perror("execlp"); /* if we get here, execlp failed */
exit(1);
}
最佳答案
阅读信号。当您从父进程启动新进程时,您将需要发送一个信号来终止旧的子进程。当有人键入 ctrl+c 时,您的程序将从操作系统收到信号。您可能还需要捕获从操作系统获得的信号并进行一些清理(例如杀死旧的子进程)。
参见,例如http://linux.die.net/man/2/signal
此外,显然,您需要重写程序,以便它永远不会退出,除非它收到该信号。
关于模拟调度程序的 C 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32554427/