C program to illustrate the race condition

race condition occurs when multiple processes are trying to do something with shared data and the final outcome depends on the order in which the processes run. It is also defined as; an execution ordering of concurrent flows that results in undesired behavior is called a race condition-a software defect and frequent source of vulnerabilities.

Race condition is possible in runtime environments, including operating systems that must control access to shared resources, especially through process scheduling.

Avoid Race Condition:
If a process wants to wait for a child to terminate, it must call one of the wait functions. If a process wants to wait for its parent to terminate, a loop of the following form could be used

while( getppid() != 1 )
The problem with this type of loop (called polling) is that it wastes CPU time, since the caller is woken up every second to test the condition. To avoid race conditions and to avoid polling, some form of signaling is required between multi processes.

fork() function:
An existing process can create a new one by calling the fork function..The new process created by fork is called the child process.This function is called once but returns twice.The only difference in the returns is that the return value in the child is 0, whereas the return value in the parent is the process ID of the new child.The reason the child’s process ID is returned to the parent is that a process can have more than one child, and there is no function that allows a process to obtain the process IDs of its children.The reason fork returns 0 to the child is that a process can have only a single parent, and the child can always call getppid to obtain the process ID of its parent. (Process ID 0 is reserved for use by the kernel, so it’s not possible for 0 to be the process ID of a child.)Both the child and the parent continue executing with the instruction that follows the call to fork.The parent and the child share the text segment.

static void charatatime(char *);
int main(void)
pid_t pid;
if ((pid = fork()) < 0)
printf("fork error");
else if (pid == 0)
charatatime("output from child\n");
charatatime("output from parent\n");
return 0;
static void charatatime(char *str)
char *ptr;
int c;
setbuf(stdout, NULL); /* set unbuffered */
for (ptr = str; (c = *ptr++) != 0; )
putc(c, stdout);

Leave a Reply