Search code examples
cmultithreadingshellsingle-threaded

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. 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)? 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?

Can someone tell me how the aforementioned code works in thread level?


Solution

  • The system() function context means the main process is spawning a child process only to immediately wait for its termination. So we can think 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. Then it will spawn another child process, execute utily cmd2, wait for cmd2 termination.

    No thread level in this context. Thread is a unit of execution in a process. A process can contains one or more threads.