Attached is an example C program using fork(2). It dynamically 
allocates a string array with malloc(3), then forks. Child free(3)s the 
array, sleep(3)s for 3 seconds, then exits. Parent wait(2)s for 
children, then prints the array. The array in the parent is not 
affected by free(3) in the child.
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>

#define NSTRINGS 5
#define SLEN     255

int
main(int argc, char** argv)
{
	char** strings = NULL;
	pid_t pid;
	int i;

	strings = malloc(NSTRINGS * sizeof(char*));
	if (!strings)
	{
		perror("malloc");
		exit(errno);
	}
	for (i = 0; i < NSTRINGS; i++)
	{
		strings[i] = malloc(SLEN+1);
		if (!strings[i])
		{
			perror("malloc");
			exit(errno);
		}
	}
	memccpy(strings[0], "Hello, world!", 0, SLEN);
	memccpy(strings[1], "This is an example", 0, SLEN);
	memccpy(strings[2], "of a string", 0, SLEN);
	memccpy(strings[3], "array holding", 0, SLEN);
	memccpy(strings[4], "some strings", 0, SLEN);

	pid = fork();
	if (pid > 0)
	{
		/* Parent */
		pid_t wpid;
		int status;

		printf("parent: Waiting for children...\n");
		fflush(stdout);
		wpid = wait(&status);
		if (wpid < 0)
		{
			perror("wait");
			exit(errno);
		}
		printf("parent: Done waiting for children.\n");
		fflush(stdout); /* <-- we don't exit from parent here, */
				/*     continuing after this if        */
	}
	else if (pid == 0)
	{
		/* Child */
		for (i = 0; i < NSTRINGS; i++)
			free(strings[i]);
		free(strings);
		printf("child: Sleeping for 3 seconds...\n");
		fflush(stdout);
		sleep(3);
		printf("child: Done sleeping.\n");
		fflush(stdout);
		exit(0); /* <-- we exit from child here, not continuing */
			 /*     the rest of the function main           */
	}

	/* Continued, in parent */
	for (i = 0; i < NSTRINGS; i++)
		printf("string #%d: \"%s\"\n", i, strings[i]);
	for (i = 0; i < NSTRINGS; i++)
		free(strings[i]);
	free(strings);
	return 0;
}

Reply via email to