How do you spawn another process in C?

It really depends on what you’re trying to do, exactly, as it’s:

  1. OS dependent
  2. Not quite clear what you’re trying to do.

Nevertheless, I’ll try to provide some information for you to decide.
On UNIX, fork() creates a clone of your process from the place where you called fork. Meaning, if I have the following process:

#include <unistd.h>
#include <stdio.h>

int main()
{
    printf( "hi 2 u\n" );
    int mypid = fork();

    if( 0 == mypid )
        printf( "lol child\n" );
    else
        printf( "lol parent\n" );

    return( 0 );
}

The output will look as follows:

hi 2 u
lol child
lol parent

When you fork() the pid returned in the child is 0, and the pid returned in the parent is the child’s pid. Notice that “hi2u” is only printed once… by the parent.

execve() and its family of functions are almost always used with fork(). execve() and the like overwrite the current stackframe with the name of the application you pass to it. execve() is almost always used with fork() where you fork a child process and if you’re the parent you do whatever you need to keep doing and if you’re the child you exec a new process. execve() is also almost always used with waitpid() — waitpid takes a pid of a child process and, quite literally, waits until the child terminates and returns the child’s exit status to you.

Using this information, you should be able to write a very basic shell; one that takes process names on the command line and runs processes you tell it to. Of course, shells do more than that, like piping input and output, but you should be able to accomplish the basics using fork(), execve() and waitpid().

NOTE: This is *nix specific! This will NOT work on Windows.

Hope this helped.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)