Creating a Process in C

July 17, 2007

I won’t list reasons why every programmer should know C because there have already been numerous discussions on the subject.

As a programmer, you can decide for yourself whether learning C will benefit your career.

I’ve chosen to start writing a small project in C so I can get a better knowledge of pointers, structs and memory allocation.

I’m going to share a small snippet of code which creates a process in Unix. You might find this interesting if you’ve never seen C code before.

Processes are created using the fork() function, which basically makes a copy of the existing process running and assigns a new process id (PID) to the child process. The rest of the code is fairly self explanatory.


#include <stdio.h>

/* the main() function is automatically executed… */

int main()
{

/* fork the process */

int p_id = fork();

/* this is the code the child process will execute */

if(p_id == 0)
{

/* endless loop */

for(;;)
{

printf(“Im a child processn”);
sleep(10);

}

}

/* close the parent process */

exit(0);

}

Save and compile the code using gcc (gcc process.c -o process). The process should now be listed in the process list (type ps -aux in unix).

psaux

Leave a Comment

Previous post:

Next post: