我正在尝试将一个subprocess放在睡觉状态,并在用户input一行文本以打印input的行数时将其唤醒。
我的代码工作正常。 但是,我发现奇怪的是我必须用户两个获取(str)声明,如果我没有用户将被提示只有一次。
如果运行代码和评论得到(str)你会明白我的意思。
你的帮助表示赞赏。 谢谢
#include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <wait.h> #include <unistd.h> #include <signal.h> main () { int n; char ch; pid_t child; int erret; char str[20]; int c = 0; if ((child = fork ()) < 0) { perror ("fork"); exit (0); } else { //waitpid(child,NULL,0); do { waitpid (child, NULL, 0); printf ("Enter a line(s) \n"); //funn(); //fflush(stdin); //scanf("%d",&n); gets (str); gets (str); erret = kill (child, SIGCHLD); printf ("Signal %d\n", erret); if (erret >= 0) { c++; printf ("You have entered : %d line(s)\n", c); //pause(); //waitpid(child,NULL,0); } else { kill (child, SIGKILL); exit (0); } printf ("\nPress 9 to exit :"); fflush (stdin); scanf ("%d", &n); fflush (stdin); } while (n != 9); kill (child, SIGKILL); } }
你的概念是有缺陷的,你没有指明什么是parant和孩子。 所以你有一个gets
的种族条件。 这是因为fork
调用之后,代码的两个副本运行,一个副本由父节点复制,另一个由子节点复制。 所以解决的办法是添加一个swich
或者else if
语句来将你的代码分成子节点和父节点。 顺便说一句,已经说过使用fgets
switch(fork()): case -1: //Error case 0: // Child code default: // Parant code
有很多方法可以获得重复的字符串输入,就像你正在做的那样。 其中一种标准方法是收集输入,直到用户发出EOF
信号,表示没有更多数据要输入。 (在Linux上EOF
是由终端用ctrl + d
)。 不改变你的逻辑,没有评论你的fork, waitpid, etc..
实现,以下是处理你的程序收集字符串输入的一种方法,直到用户通过在键盘上按ctrl+d
发送EOF
:
#include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <wait.h> #include <unistd.h> #include <signal.h> int main () { pid_t child; int erret; int c = 0; ssize_t nread = 0; /* number of chars read by getline */ char *lineptr = NULL; /* string read by (NULL forces getline to allocate) */ size_t nbytes = 0; /* number of bytes to read (ignored with lineptr = NULL) */ if ((child = fork ()) < 0) { perror ("fork"); exit (0); } else { waitpid (child, NULL, 0); printf ("\nEnter line(s) of text (ctrl+d to exit):\n\n"); while (printf (" Input: ") && (nread = getline (&lineptr, &nbytes, stdin) != -1)) { erret = kill (child, SIGCHLD); printf ("\n Signal %d\n", erret); if (erret >= 0) { c++; printf (" You have entered : %d line(s)\n\n", c); } else { kill (child, SIGKILL); exit (0); } } kill (child, SIGKILL); } return 0; }
输出:
$ ./bin/ind2 Enter line(s) of text (ctrl+d to exit): Input: line one Signal 0 You have entered : 1 line(s) Input: line 2 Signal 0 You have entered : 2 line(s) Input: line 3 Signal 0 You have entered : 3 line(s) Input: Killed