【发布时间】:2015-09-13 20:52:37
【问题描述】:
我正在学习 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);
}
【问题讨论】:
-
我们不是来为您工作的。请阅读每个功能的手册页,考虑它们如何适用于您的分配要求,并给它一个炙手可热的东西。如果您仍有困难,请回来提出更具体的问题。
-
@AlanAu 我不是要你为我工作。我只需要从我以前的代码开始。
-
那么请更具体地回答您的问题。您基本上只是不费吹灰之力就放弃了作业问题。你的工作是提出一个特定的问题,而不是我们的问题,以准确猜测你需要帮助的地方。
-
我想知道,我会在 forkexec 之间调用几个程序,然后在 forkexec 之后杀死每个程序。我怎样才能让程序一直运行到
ctrl-c