gpt4 book ai didi

在 C 中从终端控制进程

转载 作者:太空宇宙 更新时间:2023-11-04 04:31:10 24 4
gpt4 key购买 nike

<分区>

我有一个函数 bomb() 应该杀死一个子进程。

void bomb(id){
kill(id, SIGKILL);
printf("%d is ruined!", id);
}

它应该由用户在终端中输入“bomb 2355”(其中 2355 是子进程的 pid)来调用。怎么做?

我还被另一件事困住了。如何将所有子进程 PID 添加到 launched[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");
}

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