Create child process linux

fork (2) — Linux Man Pages

fork: create a child process

Command to display fork manual in Linux: $ man 2 fork

fork — create a child process

SYNOPSIS


DESCRIPTION

The child process and the parent process run in separate memory spaces. At the time of fork () both memory spaces have the same content. Memory writes, file mappings ( mmap (2)), and unmappings ( munmap (2)) performed by one of the processes do not affect the other.

The child process is an exact duplicate of the parent process except for the following points: * The child has its own unique process ID, and this PID does not match the ID of any existing process group ( setpgid (2)) or session. * The child’s parent process ID is the same as the parent’s process ID. * The child does not inherit its parent’s memory locks ( mlock (2), mlockall (2)). * Process resource utilizations ( getrusage (2)) and CPU time counters ( times (2)) are reset to zero in the child. * The child’s set of pending signals is initially empty ( sigpending (2)). * The child does not inherit semaphore adjustments from its parent ( semop (2)). * The child does not inherit process-associated record locks from its parent ( fcntl (2)). (On the other hand, it does inherit fcntl (2) open file description locks and flock (2) locks from its parent.) * The child does not inherit timers from its parent ( setitimer (2), alarm (2), timer_create (2)). * The child does not inherit outstanding asynchronous I/O operations from its parent ( aio_read (3), aio_write (3)), nor does it inherit any asynchronous I/O contexts from its parent (see io_setup (2)).

The process attributes in the preceding list are all specified in POSIX.1. The parent and child also differ with respect to the following Linux-specific process attributes: * The child does not inherit directory change notifications (dnotify) from its parent (see the description of F_NOTIFY in fcntl (2)). * The prctl (2) PR_SET_PDEATHSIG setting is reset so that the child does not receive a signal when its parent terminates. * The default timer slack value is set to the parent’s current timer slack value. See the description of PR_SET_TIMERSLACK in prctl (2). * Memory mappings that have been marked with the madvise (2) MADV_DONTFORK flag are not inherited across a fork (). * Memory in address ranges that have been marked with the madvise (2) MADV_WIPEONFORK flag is zeroed in the child after a fork (). (The MADV_WIPEONFORK setting remains in place for those address ranges in the child.) * The termination signal of the child is always SIGCHLD (see clone (2)). * The port access permission bits set by ioperm (2) are not inherited by the child; the child must turn on any bits that it requires using ioperm (2).

Note the following further points: * The child process is created with a single thread—the one that called fork (). The entire virtual address space of the parent is replicated in the child, including the states of mutexes, condition variables, and other pthreads objects; the use of pthread_atfork (3) may be helpful for dealing with problems that this can cause. * After a fork () in a multithreaded program, the child can safely call only async-signal-safe functions (see signal-safety (7)) until such time as it calls execve (2). * The child inherits copies of the parent’s set of open file descriptors. Each file descriptor in the child refers to the same open file description (see open (2)) as the corresponding file descriptor in the parent. This means that the two file descriptors share open file status flags, file offset, and signal-driven I/O attributes (see the description of F_SETOWN and F_SETSIG in fcntl (2)). * The child inherits copies of the parent’s set of open message queue descriptors (see mq_overview (7)). Each file descriptor in the child refers to the same open message queue description as the corresponding file descriptor in the parent. This means that the two file descriptors share the same flags ( mq_flags ). * The child inherits copies of the parent’s set of open directory streams (see opendir (3)). POSIX.1 says that the corresponding directory streams in the parent and child may share the directory stream positioning; on Linux/glibc they do not.

Читайте также:  Как вернуть первоначальные настройки windows

RETURN VALUE


ERRORS


CONFORMING TO


NOTES

Under Linux, fork () is implemented using copy-on-write pages, so the only penalty that it incurs is the time and memory required to duplicate the parent’s page tables, and to create a unique task structure for the child.

Источник

YoLinux Tutorial: Fork, Exec and Process control

This tutorial will cover the creation of child processes and process control using fork, exec and other C library function calls using the GNU «C» compiler on the Linux operating system.

Related YoLinux Tutorials:

The fork() system call will spawn a new child process which is an identical process to the parent except that has a new system process ID. The process is copied in memory from the parent and a new process structure is assigned by the kernel. The return value of the function is which discriminates the two threads of execution. A zero is returned by the fork function in the child’s process.

The environment, resource limits, umask, controlling terminal, current working directory, root directory, signal masks and other process resources are also duplicated from the parent in the forked child process.

Compile: g++ -o ForkTest ForkTest.cpp
Run: ForkTest

[Potential Pitfall] : Some memory duplicated by a forked process such as file pointers, will cause intermixed output from both processes. Use the wait() function so that the processes do not access the file at the same time or open unique file descriptors. Some like stdout or stderr will be shared unless synchronized using wait() or some other mechanism. The file close on exit is another gotcha. A terminating process will close files before exiting. File locks set by the parent process are not inherited by the child process.

[Potential Pitfall] : Race conditions can be created due to the unpredictability of when the kernel scheduler runs portions or time slices of the process. One can use wait(). the use of sleep() does not guarentee reliability of execution on a heavily loaded system as the scheduler behavior is not predictable by the application.

Note on exit() vs _exit(): The C library function exit() calls the kernel system call _exit() internally. The kernel system call _exit() will cause the kernel to close descriptors, free memory, and perform the kernel terminating process clean-up. The C library function exit() call will flush I/O buffers and perform aditional clean-up before calling _exit() internally. The function exit(status) causes the executable to return «status» as the return code for main(). When exit(status) is called by a child process, it allows the parent process to examine the terminating status of the child (if it terminates first). Without this call (or a call from main() to return()) and specifying the status argument, the process will not return a value.

The vfork() function is the same as fork() except that it does not make a copy of the address space. The memory is shared reducing the overhead of spawning a new process with a unique copy of all the memory. This is typically used when using fork() to exec() a process and terminate. The vfork() function also executes the child process first and resumes the parent process when the child terminates.

Читайте также:  Windows defender последняя версия

Compile: g++ -o VForkTest VForkTest.cpp
Run: VForkTest

Note: The child process executed first, updated the variables which are shared between the processes and NOT unique, and then the parent process executes using variables which the child has updated.

[Potential Pitfall] : A deadlock condition may occur if the child process does not terminate, the parent process will not proceed.

  • vfork — create a child process and block parent
  • _exit — — terminate the current process

The function clone() creates a new child process which shares memory, file descriptors and signal handlers with the parent. It implements threads and thus launches a function as a child. The child terminates when the parent terminates.
See the YoLinux POSIX threads tutorial

The parent process will often want to wait until all child processes have been completed. this can be implemented with the wait() function call.

wait(): Blocks calling process until the child process terminates. If child process has already teminated, the wait() call returns immediately. if the calling process has multiple child processes, the function returns when one returns.

waitpid(): Options available to block calling process for a particular child process not the first one.

Avoids orphaned process group when parent terminates. When parent dies, this will be a zombie. (No parent process. Parent=1) Instead, create a new process group for the child. Later process the group is terminated to stop all spawned processes. Thus all subsequent processes should be of this group if they are to be terminated by the process group id. Process group leader has the same process id and group process id. If not changed then the process group is that of the parent. Set the process group id to that of the child process.

The macro testing for __gnu_linux__ is for cross platform support as man other OS’s use a different system call.

  • setpgid/getpgid setpgrp/getpgrp — set process group
  • setsid — creates a session and sets the process group ID
  • getuid/geteuid — get user identity
  • setgid — set group identity
  • getgid/getegid — get group (real/effective) identity
  • setreuid/setregid — set real user or group identity
  • errno — number of last error

Kill all processes in a process group:

See /usr/include/bits/signum.h for list of signals.

Man Pages:

  • killpg — send signal to a process group
  • kill — send signal to a process
  • signal (2) — ANSI C signal handling
  • signal (7) — List of available signals
  • sigaction — POSIX signal handling functions.
  • pause (2) — wait for signal
  • raise (3) — send a signal to a current process

The system() call will execute an OS shell command as described by a character command string. This function is implemented using fork(), exec() and waitpid(). The command string is executed by calling /bin/sh -c command-string. During execution of the command, SIGCHLD will be blocked, and SIGINT and SIGQUIT will be ignored. The call «blocks» and waits for the task to be performed before continuing.

The popen() call opens a process by creating a pipe, forking, and invoking the shell (bourne shell on Linux). The advantage to using popen() is that it will allow one to interrogate the results of the command issued.

This example opens a pipe which executes the shell command «ls -l«. The results are read and printed out.

The second argument to popen:

  • r: Read from stdin (command results)
  • w: write to stdout (command)
  • For stderr: command=»ls -l 2>&1″,»w»);

The exec() family of functions will initiate a program from within a program. They are also various front-end functions to execve().

The functions return an integer error code. (0=Ok/-1=Fail).

execl() and execlp():

int execl(const char *path, const char *arg0, const char *arg1, const char *arg2, . const char *argn, (char *) 0);

Читайте также:  Mac os как удалять пользователей через терминал

The routine execlp() will perform the same purpose except that it will use environment variable PATH to determine which executable to process. Thus a fully qualified path name would not have to be used. The first argument to the function could instead be «ls». The function execlp() can also take the fully qualified name as it also resolves explicitly.

execv() and execvp():

This is the same as execl() except that the arguments are passed as null terminated array of pointers to char. The first element «argv[0]» is the command name.

int execv(const char *path, char *const argv[]);

The routine execvp() will perform the same purpose except that it will use environment variable PATH to determine which executable to process. Thus a fully qualified path name would not have to be used. The first argument to the function could instead be «ls». The function execvp() can also take the fully qualified name as it also resolves explicitly.

execve():

The function call «execve()» executes a process in an environment which it assigns.

Set the environment variables:

Man Pages:

  • strerror / strerror_r — return string describing error code
  • errno — number of last error
  • perror — print a system error message

Data File: environment_variables.conf

Man Pages:

  • execve — execute with given environment

Note: Don’t mix malloc() and new. Choose one form of memory allocation and stick with it.

Man Pages:

  • malloc — Dynamically allocate memory
  • free — Free allocated memory
«UNIX Network Programming, Volume 1: Sockets Networking API» Third Edition
by W. Richard Stevens, Bill Fenner, Andrew M. Rudoff, Richard W. Stevens
ISBN # 0131411551, Addison-Wesley Pub Co; 3 edition (October 22, 2003)

This book covers POSIX, IPv6, network APIs, sockets (elementary, advanced, routed, and raw), multicast, UDP, TCP, Threads, Streams, ioctl. In depth coverage of topics.

«UNIX Network Programming, Volume 1: Networking APIs — Sockets and XTI» Second Edition
by W. Richard Stevens
ISBN # 013490012X, Prentice Hall PTR

This book covers network APIs, sockets + XTI, multicast, UDP, TCP, ICMP, raw sockets, SNMP, MBONE. In depth coverage of topics.

«UNIX Network Programming Volume 2: Interprocess Communications»
by W. Richard Stevens
ISBN # 0130810819, Prentice Hall PTR

This book covers semaphores, threads, record locking, memory mapped I/O, message queues, RPC’s, etc.

«Advanced Linux Programming»
by Mark Mitchell, Jeffrey Oldham, Alex Samuel, Jeffery Oldham
ISBN # 0735710430, New Riders

Good book for programmers who already know how to program and just need to know the Linux specifics. Covers a variety of Linux tools, libraries, API’s and techniques. If you don’t know how to program, start with a book on C.

«Advanced UNIX Programming» Second Edition
by Marc J. Rochkind
ISBN # 0131411543, Addison-Wesley Professional Computing Series

«Advanced Programming in the UNIX Environment» First Edition
by W. Richard Stevens
ISBN # 0201563177, Addison-Wesley Professional Computing Series

It is the C programmers guide to programming on the UNIX platform. This book is a must for any serious UNIX/Linux programmer. It covers all of the essential UNIX/Linux API’s and techniques. This book starts where the basic C programming book leaves off. Great example code. This book travels with me to every job I go to.

«Advanced Unix Programming»
by Warren W. Gay
ISBN # 067231990X, Sams White Book Series

This book covers all topics in general: files, directories, date/time, libraries, pipes, IPC, semaphores, shared memory, forked processes and I/O scheduling. The coverage is not as in depth as the previous two books (Stevens Vol 1 and 2)

«Linux Programming Bible»
by John Goerzen
ISBN # 0764546570, Hungry Minds, Inc

This covers the next step after «C» programming 101.

Источник

Оцените статью