简体   繁体   English

单线程程序是否在多个线程上执行? [C]

[英]Is single threaded program executing on multiple threads? [C]

If I execute the following code which is single threaded: 如果我执行以下单线程代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[])
{
  char[] cmd1 = "cat /sys/class/thermal/thermal_zone0/temp > temp.txt";
  char[] cmd2 = "cat /sys/class/thermal/thermal_zone2/temp > temp2.txt";
  system(cmd1);
  system(cmd2);
  return 0;
}

I was under the assumption that the aforementioned code is a single threaded user-level application. 我当时假设上述代码是单线程用户级应用程序。 When the program executes, especially the system() function, which requires to execute the shell command. 当程序执行时,尤其是system()函数,该函数需要执行shell命令。 So when this program calls two shell command functions are they being executed on two different threads (a thread for this program and another thread executed by shell)? 那么,当该程序调用两个shell命令函数时,它们是在两个不同的线程(该程序的一个线程和另一个由shell执行的线程)上执行的吗? Or when system() function is called the operation passes the control to shell, which is then preempted and executes the command and then hands back the operation to the program thread? 还是调用system()函数时,该操作将控制权传递给了外壳程序,然后该外壳程序被抢占并执行命令,然后将该操作交还给程序线程?

Can someone tell me how the aforementioned code works in thread level? 有人可以告诉我上述代码在线程级别如何工作吗?

The system() function context means the main process is spawning a child process only to immediately wait for its termination. system()函数上下文意味着主进程正在生成一个子进程,只是为了立即等待其终止。 So we can think system() = fork() -> exec() -> waitpid(). 因此我们可以认为system()= fork()-> exec()-> waitpid()。 In your situation: 在您的情况下:

char[] cmd1 = "cat /sys/class/thermal/thermal_zone0/temp > temp.txt";
char[] cmd2 = "cat /sys/class/thermal/thermal_zone2/temp > temp2.txt";
system(cmd1);
system(cmd2);

The main process will spawn new child process, execute the utility cmd1, wait for cmd1 termination. 主进程将生成新的子进程,执行实用程序cmd1,等待cmd1终止。 Then it will spawn another child process, execute utily cmd2, wait for cmd2 termination. 然后它将生成另一个子进程,执行utily cmd2,等待cmd2终止。

No thread level in this context. 在这种情况下没有线程级别。 Thread is a unit of execution in a process. 线程是进程中执行的单元。 A process can contains one or more threads. 一个进程可以包含一个或多个线程。

On Linux, threads and Processes are similar - they are called tasks. 在Linux上,线程和进程是相似的-它们称为任务。 In Linux, a thread is simply a process sharing few things with other process(s). 在Linux中,线程只是一个与其他进程共享少量内容的进程。 The system() function call is a blocking one and your program waits when the system() finishes its work. system()函数调用是一个阻塞的调用,当system()完成工作时,程序将等待。 system() produces a new process which is killed when the work is completed. system()产生一个新进程,当工作完成时,该进程将被终止。

You can say that total three processes were created in a sequential manner. 您可以说总共有三个流程是按顺序创建的。 But since nothing was shared between the processes - they were not threads. 但是,由于进程之间没有共享任何内容-它们不是线程。

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

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