Skip to content

Instantly share code, notes, and snippets.

@k-popov
Last active August 29, 2015 14:17
Show Gist options
  • Save k-popov/2df8bc24fe3d857748cb to your computer and use it in GitHub Desktop.
Save k-popov/2df8bc24fe3d857748cb to your computer and use it in GitHub Desktop.
#define _GNU_SOURCE
#include <sys/wait.h>
#include <sys/utsname.h>
#include <sched.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/sem.h>
#include <sys/ipc.h>
#include <sys/types.h>
#include <sys/types.h>
#include <sys/capability.h>
#define errExit(msg) do { perror(msg); exit(EXIT_FAILURE); \
} while (0)
#define COMMON_SEM_KEY 31338
static int /* Start function for cloned child */
childFunc()
{
printf("PID from child point of view just after clone() is %ld\n", (long) getpid());
printf("example_sem_id in child is %ld\n",
(long) semget(COMMON_SEM_KEY, 1, IPC_CREAT | IPC_EXCL));
sleep(1);
return 0; /* Terminates child */
}
#define STACK_SIZE (1024 * 1024) /* Stack size for cloned child */
static char child_stack[STACK_SIZE];
int
main(int argc, char *argv[])
{
printf("example_sem_id in parent is %ld\n",
(long) semget(COMMON_SEM_KEY, 1, IPC_CREAT|IPC_EXCL));
pid_t child_pid;
child_pid = clone(childFunc,
child_stack + STACK_SIZE, /* Points to start of
downwardly growing stack */
CLONE_NEWIPC | SIGCHLD, NULL);
printf("PID of child created by clone() is %ld\n", (long) child_pid);
if (waitpid(child_pid, NULL, 0) == -1) /* Wait for child */
errExit("child wait failed");
exit(EXIT_SUCCESS);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment