模拟调度程序的 C 程序

标签 c linux exec fork

我正在学习 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/

相关文章:

plugins - 在执行 mvn clean install 时如何使用 main() 运行类

java - 使用 Pump StreamHandler 将输出和错误写入日志文件

c - 跟踪工具提示导致重绘速度极其缓慢的灰色 "trail"

c - 如何声明指向文件的动态指针数组

c - C 中的通用列表包含垃圾值

c - _do_fork() 如何返回两个不同的 PID(一个用于父进程,一个用于子进程)

linux - 如何检测系统是否在 UNIX shell 脚本中启用了 IPv6?

linux - 将 FIND 命令的结果导出到 linux shell 脚本中的变量值?

linux - tmux 捕获 Pane 没有正确打印所有文本,而是在几个字符后插入换行符

java - 从 webapp 执行外部 Java 程序