C编程 – Scanf无法在ubuntu中运行

我正在Ubuntu 10中编写一个C程序来创建进程,显示进程ID并终止进程。 我正在使用kill()命令来终止用户通过scanf输入的进程ID。 但是,scanf根本不起作用。 我尝试在%d之前添加“空格”但没有发生任何事情。 感谢是否有人可以提供帮助!

以下是我的代码:

include  include  include  include  include  main () { int x; int pid[10]; // to store fork return value int p[10]; // to store process ID // Create 5 new processes and store its process ID for (x=1;x<=5;x++) { if ((pid[x]=fork())==0) { p[x]=getpid(); printf("\n I am process: %d, my process ID: %d\n",x,p[x]); // Display process number and PID } else exit(0); } { int y; y=p[x]; printf("Please enter a process ID to kill: "); scanf(" %d", &y); //waiting for user input printf("\nThe process %d is killed.\n",y); kill(y,9); //Values 9 represents SIGKILL } } 

您的父进程退出,之后生成的每个进程也会退出(fork的返回值不同于1,因此它们退出)。 如果一个进程没有父进程,它就变成了一个“孤儿”,并且由OS进行特殊处理(其他一些进程采用它)。 你确定这是你正在寻找的行为吗?

编辑:这可能是你的意思:

 #include  #include  #include  #include  #include  int main () { int x; int pid[10]; // to store fork return value pid_t parent = getpid(); // Create 5 new processes and store its process ID for (x=1;x<=5;x++) { if ((pid[x]=fork())!=0) { printf("\n I spawned process: %d, its process ID: %d\n",x,pid[x]); // Display process number and PID }else{ while(1){} } } if(getpid() == parent){ int y; y=pid[x]; printf("Please enter a process ID to kill: "); scanf(" %d", &y); //waiting for user input printf("\nThe process %d is killed.\n",y); kill(y,9); //Values 9 represents SIGKILL }else{ printf("THIS SHOULD NOT HAPPEN!"); } return 0; } 

fork返回两次,每次都在不同的进程中。 关于这两个过程的一个非常重要的事情是它们不共享内存。 这意味着通过调用子进程中的getpid并将其保存在数组中,您无法在父变量的副本中看到该值。

你最想做的事情是这样的:

 for (...) { if ((pid[x]=fork()) == 0) { printf("child created, pid = %d\n", getpid()); while(1) sleep(1000); /* children will never run outside this loop */ } else { continue; } } /* this code only runs in the parent */