【发布时间】:2016-07-07 03:05:15
【问题描述】:
我有一个函数 bomb() 应该杀死一个子进程。
void bomb(id){
kill(id, SIGKILL);
printf("%d is ruined!", id);
}
它应该由终端中的用户输入调用,例如“bomb 2355”(其中 2355 是子进程的 pid)。怎么做?
我还纠结于另一件事。如何将所有子进程 PID 添加到启动的数组中[10]?那么,如果 command == "status" 可以访问它吗?
我是 C.. 的新手。在互联网上到处搜索 :( 完整的代码,如果在下面。 将不胜感激任何帮助!谢谢!
char planes();
void plane_function();
void refuel();
void bomb(int id);
void handle_signal(int signo);
char command[12];
int launched[10];
int main ()
{
planes();
return 0;
}
char planes(){
printf("Enter a command: ");
scanf("%s", command);
pid_t main_process; //main process created
//struct sigaction sa; //handling signals
//printf("My pid is: %d\n", getpid());
if (strcmp(command, "launch") == 0){
main_process = fork();
if (main_process == 0){
printf ("the main process ID is %d\n", getppid()); // main_process ID
printf ("the new plane ID is %d\n", getpid()); // child ID
//printf("launched: %d", launched[n]);
launched[0] = getpid();
plane_function(launched[0], main_process);
}
else
{
//printf("Parent");
}
}
else if (strcmp(command, ("bomb")) == 0){ // how to access a PID
printf("Bomb N\n");
bomb(plane_id);
}
else if (strcmp(command, "refuel") == 0){
printf("Refuel N\n");
}
else if (strcmp(command, "status") == 0){
printf("STATUS: \n");
printf("Planes launched: \n");
printf("%d\n ", launched[0]);
}
else if (strcmp(command, "quit") == 0){
printf("Quit\n");
}
else {
printf("Error! Wrong command!\n");
}
planes();
return 0;
}
void plane_function(id) {
int fuel = 100;
while (fuel >= 15){
sleep(3);
fuel = fuel - 15;
printf("Bomber %d to base. Fuel left: %d\n", id, fuel);
if(fuel == 10){
printf("%d, you're done kid\n", id);
kill(id, SIGKILL);
}
}
}
void bomb(id){
kill(id, SIGKILL);
printf("%d is ruined!", id);
}
void handle_signal(int signo){
const char *signal_name;
sigset_t pending;
printf("SIGNAL!!!!");
if (signo == SIGUSR1)
printf("received SIGUSR1\n");
else if (signo == SIGKILL)
printf("received SIGKILL\n");
}
【问题讨论】:
-
使用
kill <pid>有什么问题? -
进程应该被来自终端的命令杀死,比如“bomb N”,其中 N 是 pid,而不是“kill N”。
-
如果您只想使用不同的名称,请使用别名。
-
@Olaf - 这似乎是关于用户 I/O 和
fork/kill系统调用语义的问题,not“如何杀死进程从一个壳”。 -
@BrianMcFarland:也许吧。但在我看来,用户对此并不十分清楚。无论如何,这个问题实际上是要求指导一些 C 特性。它也太宽泛了。
标签: c parent pid kill child-process