Linux fork all threads

Многозадачность в Linux. Язык программирования C. Статья 2 (функция fork)

Здесь весь мой канал Old Programmer . Здесь: Программирование. Тематическое оглавление моего Zen-канала (Old Programmer) . А здесь собраны все ссылки по C и C++. А здесь перечень ссылок на ресурсы, посвященные многозадачности.

Сегодня продолжаем многозадачную тему. Будем рассматривать функцию fork() . Начало темы здесь .

О системной функции fork()

В линуксовой многозадачности fork() , пожалуй, тема самая сложная. Во всяком случае, сразу это в голове не укладывается. Но я придерживаюсь очень простого принципа. Для использования какой либо технологии не обязательно понимать все о ней. Практика постепенно приведет вас к этому пониманию.

Функция fork() создает копию данного процесса. Эта копия называется дочерним процессом . Дочерний процесс получает в свое распоряжение практически все от родительского . Это очень важный вопрос (что все таки он получает, а что нет), но я пока не буду на этом останавливаться. Для простых программ, это пока не важно. Код дочернего процесса, как и код родительского, продолжают выполняться с инструкции, следующей после вызова функции fork() . В результате действительно fork() это вилка.

Пример использования функции fork() в Linux

Рассмотрим программу multi1010.c . Компилируется она обычным образом:

Интерпретация выполнения этой программы как раз позволяет нам понимать, как работает функция fork() . Суть ситуации заключается в том, что в родительском процессе переменная t получает значение, равное идентификатору дочернего процесса , а в дочернем процессе переменная t равна нулю . Вот это и позволяет в коде «определять» поведение дочернего и родительского процессов. Условной конструкцией if(!t) мы и разделяем обработку для родительского и дочернего процессов.

Ну и, наконец, две функции getpid() — получить идентификатор текущего процесса, getppid() — получить идентификатор родительского процесса. Соответственно, идентификатор getpid() в родительском процессе, совпадает с идентификатором getppid() в дочернем процессе. Ну а значение getpid() в дочернем процессе совпадет со значением переменной t в родительском. Такие дела.

Результат выполнения программы:

До 89
После 89
Родительский 16773
Дочерний 16774
После 89
Дочерний 16774
Родительский 16773

Объясните ка, почему строка ‘ До 89 ‘ появляется в листинге один раз, а строка ‘ После 89 ‘ дважды.

При использовании функции fork необходимо отслеживать дочерние процессы. Когда дочерний процесс завершается, связь его с родителем сохраняется, пока родительский процесс не завершится или не вызовет функцию wait . Т.е. дочерний процесс остается в системе, являясь «зомби» — процессом.

Следующая статья о многозадачности здесь .

Многозадачность это когда у тебя ребенок на одной руке, телефонная трубка в другой, а ты при этом переворачиваешь блины на сковороде, одновременно крася ногти. Обычный день женщины.

Подписываемся на мой канал Old Programmer .

Источник

Linux fork all threads

The fork() , fork1() , forkall() , forkx() , and forkallx() functions create a new process. The address space of the new process (child process) is an exact copy of the address space of the calling process (parent process). The child process inherits the following attributes from the parent process: o real user ID, real group ID, effective user ID, effective group ID o environment o open file descriptors o close-on-exec flags (see exec (2)) o signal handling settings (that is, SIG_DFL , SIG_IGN , SIG_HOLD , function address) o supplementary group IDs o set-user-ID mode bit o set-group-ID mode bit o profiling on/off status o nice value (see nice (2)) o scheduler class (see priocntl (2)) o all attached shared memory segments (see shmop (2)) o process group ID — memory mappings (see mmap (2)) o session ID (see exit (2)) o current working directory o root directory o file mode creation mask (see umask (2)) o resource limits (see getrlimit (2)) o controlling terminal o saved user ID and group ID o task ID and project ID o processor bindings (see processor_bind (2)) o processor set bindings (see pset_bind (2)) o process privilege sets (see getppriv (2)) o process flags (see getpflags (2)) o active contract templates (see contract (4))

Читайте также:  Ноутбук сенсорный экран linux

Scheduling priority and any per-process scheduling parameters that are specific to a given scheduling class might or might not be inherited according to the policy of that particular class (see priocntl (2)). The child process might or might not be in the same process contract as the parent (see process (4)). The child process differs from the parent process in the following ways: o The child process has a unique process ID which does not match any active process group ID . o The child process has a different parent process ID (that is, the process ID of the parent process). o The child process has its own copy of the parent’s file descriptors and directory streams. Each of the child’s file descriptors shares a common file pointer with the corresponding file descriptor of the parent. o Each shared memory segment remains attached and the value of shm_nattach is incremented by 1. o All semadj values are cleared (see semop (2)). o Process locks, text locks, data locks, and other memory locks are not inherited by the child (see plock (3C) and memcntl (2)). o The child process’s tms structure is cleared: tms_utime , stime , cutime , and cstime are set to 0 (see times (2)). o The child processes resource utilizations are set to 0; see getrlimit (2). The it_value and it_interval values for the ITIMER_REAL timer are reset to 0; see getitimer (2). o The set of signals pending for the child process is initialized to the empty set. o Timers created by timer_create (3C) are not inherited by the child process. o No asynchronous input or asynchronous output operations are inherited by the child. o Any preferred hardware address tranlsation sizes (see memcntl (2)) are inherited by the child. o The child process holds no contracts (see contract (4)).

Record locks set by the parent process are not inherited by the child process (see fcntl (2)).

Читайте также:  Find windows files in linux

Although any open door descriptors in the parent are shared by the child, only the parent will receive a door invocation from clients even if the door descriptor is open in the child. If a descriptor is closed in the parent, attempts to operate on the door descriptor will fail even if it is still open in the child.

Threads

A call to forkall() or forkallx() replicates in the child process all of the threads (see thr_create (3C) and pthread_create (3C)) in the parent process. A call to fork1() or forkx() replicates only the calling thread in the child process.

A call to fork() is identical to a call to fork1() ; only the calling thread is replicated in the child process. This is the POSIX-specified behavior for fork() .

In releases of Solaris prior to Solaris 10, the behavior of fork() depended on whether or not the application was linked with the POSIX threads library. When linked with -lthread (Solaris Threads) but not linked with -lpthread (POSIX Threads), fork() was the same as forkall() . When linked with -lpthread , whether or not also linked with -lthread , fork() was the same as fork1() .

Prior to Solaris 10, either -lthread or -lpthread was required for multithreaded applications. This is no longer the case. The standard C library provides all threading support for both sets of application programming interfaces. Applications that require replicate-all fork semantics must call forkall() or forkallx() .

Fork Extensions

The forkx() and forkallx() functions accept a flags argument consisting of a bitwise inclusive-OR of zero or more of the following flags, which are defined in the header :

Do not post a SIGCHLD signal to the parent process when the child process terminates, regardless of the disposition of the SIGCHLD signal in the parent. SIGCHLD signals are still possible for job control stop and continue actions if the parent has requested them.

Do not allow wait-for-multiple-pids by the parent, as in wait() , waitid ( P_ALL ), or waitid ( P_PGID ), to reap the child and do not allow the child to be reaped automatically due the disposition of the SIGCHLD signal being set to be ignored in the parent. Only a specific wait for the child, as in waitid ( P_PID , pid ), is allowed and it is required, else when the child exits it will remain a zombie until the parent exits.

If the flags argument is 0 forkx() is identical to fork() and forkallx() is identical to forkall() .

fork() Safety

If a multithreaded application calls fork() , fork1() , or forkx() , and the child does more than simply call one of the exec (2) functions, there is a possibility of deadlock occurring in the child. The application should use pthread_atfork (3C) to ensure safety with respect to this deadlock. Should there be any outstanding mutexes throughout the process, the application should call pthread_atfork() to wait for and acquire those mutexes prior to calling fork() , fork1() , or forkx() . See «MT-Level of Libraries» on the attributes (5) manual page.

Читайте также:  Building shared libraries on linux

The pthread_atfork() mechanism is used to protect the locks that libc (3LIB) uses to implement interfaces such as malloc (3C). All interfaces provided by libc are safe to use in a child process following a fork() , except when fork() is executed within a signal handler.

The POSIX standard (see standards (5)) requires fork to be Async-Signal-Safe (see attributes (5)). This cannot be made to happen with fork handlers in place, because they acquire locks. To be in nominal compliance, no fork handlers are called when fork() is executed within a signal context. This leaves the child process in a questionable state with respect to its locks, but at least the calling thread will not deadlock itself attempting to acquire a lock that it already owns. In this situation, the application should strictly adhere to the advice given in the POSIX specification: «To avoid errors, the child process may only execute Async-Signal-Safe operations until such time as one of the exec (2) functions is called.»

RETURN VALUES

Upon successful completion, fork() , fork1() , forkall() , forkx() , and forkallx() return 0 to the child process and return the process ID of the child process to the parent process. Otherwise, (pid_t)-1 is returned to the parent process, no child process is created, and errno is set to indicate the error.

ERRORS

The fork() , fork1() , forkall() , forkx() , and forkallx() functions will fail if:

EAGAIN A resource control or limit on the total number of processes, tasks or LWPs under execution by a single user, task, project, or zone has been exceeded, or the total amount of system memory available is temporarily insufficient to duplicate this process.

ENOMEM There is not enough swap space.

EPERM The < PRIV_PROC_FORK >privilege is not asserted in the effective set of the calling process.

The forkx() and forkallx() functions will fail if:

EINVAL The flags argument is invalid.

ATTRIBUTES

See attributes (5) for descriptions of the following attributes:

ATTRIBUTE TYPEATTRIBUTE VALUE
Interface StabilityCommitted
MT-Level
Standard

SEE ALSO


NOTES

An applications should call _exit() rather than exit (3C) if it cannot execve() , since exit() will flush and close standard I/O channels and thereby corrupt the parent process’s standard I/O data structures. Using exit (3C) will flush buffered data twice. See exit (2).

The thread in the child that calls fork() , fork1() , or fork1x() must not depend on any resources held by threads that no longer exist in the child. In particular, locks held by these threads will not be released.

In a multithreaded process, forkall() in one thread can cause blocking system calls to be interrupted and return with an EINTR error.

Источник

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