简体   繁体   English

等待用户输入的进程实际发生了什么?

[英]What actually happens to a process waiting for user input?

I want to know what actually happens to a process waiting for user input. 我想知道等待用户输入的进程实际发生了什么。 Lets say, in my code I gave call to scanf() to read user input from console. 可以说,在我的代码中,我调用了scanf()来从控制台读取用户输入。 It will internally call read() system call. 它将在内部调用read()系统调用。 But in this case there is no data to read until user gives any input. 但在这种情况下,在用户提供任何输入之前,没有数据可供读取。 So is our process sleeping till then? 那么我们的过程一直在睡觉吗?

Yes, it's sleeping (in OS X, at least). 是的,它正在睡觉(至少在OS X中)。

Try compiling and running the following C program: 尝试编译并运行以下C程序:

#include <stdio.h>

int main() {
    int x;
    puts("Enter a number:");
    if (scanf("%d",&x)) {
        printf("You entered %d\n",x);
    }
    else {
        puts("That isn't a number");
    }
    return 0;
}

Start the program running in the console, then open another console and enter ps -v at the command line. 启动在控制台中运行的程序,然后打开另一个控制台并在命令行输入ps -v You should see something like this: 你应该看到这样的东西:

  PID STAT      TIME  SL  RE PAGEIN      VSZ    RSS   LIM     TSIZ  %CPU %MEM COMMAND
19544 S      0:00.01   0   0      0  2463084   1596     -        0   0.0  0.0 -bash
19574 S      0:00.01   0   0      0  2454892   1568     -        0   0.0  0.0 -bash
19582 S+     0:00.00   0   0      0  2434816    676     -        0   0.0  0.0 ./a

Here, ./a is the name of the program. 这里,。/ ./a是程序的名称。 The entry for this process in the STAT column is S+ , which means the process is sleeping ( S ) and is in the foreground ( + ). STAT列中此过程的条目是S+ ,这意味着进程正在休眠( S )并且位于前台( + )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM