Can I call dup2 after vfork? - c

I want to vfork() a child process, but have its stdout be different than the parent's stdout.
The obvious way to achieve this with fork() would be to dup2() (and close() the original file descriptor) in the child after forking.
Let's say I have the file descriptor ready before calling vfork() and just need to call these two system calls before calling an exec*() function. Am I allowed to do that?

My answer is probably yes.
Based on Linux manual, A call to vfork() is equivalent to calling clone(2) with flags specified as:
CLONE_VM | CLONE_VFORK | SIGCHLD
Note from clone(2):
CLONE_FILES (since Linux 2.0)
If CLONE_FILES is set, the calling process and the child process share the same file descriptor table. Any file descriptor created by the calling process or by the child
process is also valid in the other process. Similarly, if one of the processes closes a file descriptor, or changes its associated flags (using the fcntl(2) F_SETFD oper‐
ation), the other process is also affected.
If CLONE_FILES is not set, the child process inherits a copy of all file descriptors opened in the calling process at the time of clone(). (The duplicated file descrip‐
tors in the child refer to the same open file descriptions (see open(2)) as the corresponding file descriptors in the calling process.) Subsequent operations that open or
close file descriptors, or change file descriptor flags, performed by either the calling process or the child process do not affect the other process.
So after vfork, file operations in child process are isolated by default.

Related

If the child process alters its file descriptor table, does it affect the parent's?

I'm writing a C program that involves forking a child process to call dup2 to intercept stdout to write to a file. I was wondering if the child process alters the file descriptor table for the parent process if I call dup2(fd, 1). Would it alter the FD table for the parent, or because the child has a copy of the table it would be fine?
No, it doesn't, and that's the point. If you seek an fd, it affects the parent though, because it really is two handles to the same open file descriptor.

Will exec() called after fork() cause data loss in the existing process

I am comparatively new to the linux programming. I wonder whether the exec() function called after fork() can cause data loss in the parent process.
After a successful call to fork, a new process is created which is a duplicate of the calling process. One thing that gets duplicated are the file descriptors, so it's possible for the new process to read/write the same file descriptors as the original process. These may be files, sockets, pipes, etc.
The exec function replaces the currently running program in the current process with a new program, overwriting the memory of the old program in that process. So any data stored in the memory of the old program is lost. This does not however affect the parent process that forked this process.
When a new program is executed via exec, any open file descriptors that do not have the FD_CLOEXEC (close-on-exec) flag set (see the fcntl man page) are again preserved. So now you have two processes, each possibly running a different program, which may both write to the same file descriptor. If that happens, and the processes don't properly synchronize, data written by one process to the file may overwritten by the other process.
So data loss can occur with regard to writing to file descriptors that the child process inherited from the parent process.

If a parent opens a file, then forks a child, does the child have access to the open file? (C programming) [duplicate]

This question already has answers here:
Seeking a simple description regarding 'file descriptor' after fork()
(2 answers)
Closed 6 years ago.
so I have a question regarding what a child process has access to.
If a parent open()s a file, and then fork()s a child, does the child process have access to the open file, or would it need to open the file itself? Would it be possible to have access to the already open file through shared memory between the processes? (C programming)
Short answer yes.
You can read more about it here:
http://man7.org/linux/man-pages/man2/fork.2.html
As it is said there, 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)).
* 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().
* 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(2) in a multithreaded program, the child can safely
call only async-signal-safe functions (see signal(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.
Yes, using the same file descriptor. No need for shared memory.
It would kind of work using a stdio FILE* but I would no advise doing so for files you plan to write to, as buffering in the two separate processes would lead to unexpected and confusing results.
To prevent this sharing of file descriptors - if you want to - you can of course call close() on the file descriptor as soon as the fork() call returns 0.

As a process child, how to know which file descriptor is parents

I am attempting to write a program which forks and waits for his child to finish, then the child does some work on an input and then forks the same way it's parent does and so on.
Now, I know that forking copies to the child the array of file descriptors and that I should close the ones associated with the parent, but I can't figure out which are the parents. Do I need to give to my child it's parents pid?
I've been trying to wrap my head around it for the better part of an hour and I think I have some kind of a mind block because I can't come to a conclusion.
TL;DR: As a child process how do I know which file descriptors belong to my parent?
Just after the fork (and before any exec function) your child process has the same state as its parent process (except for the result of the fork, which is 0 only in the child). So you know what are the file descriptors, since you have coded the program running in parent&child. On Linux you might also read the /proc/self/fd/ directory, see proc(5).
You might close most file descriptors after the fork and before the exec; you could code something like
for (int fd=3; fd<64; fd++) (void) close(fd);
we are starting from 3 which is after STDERR_FILENO which is 2, and we are stopping arbitrarily at 64, and the cast to (void) on the close call means to the reader that we don't care about failing close.... Of course, if you have e.g. some pipe(7)-s to communicate between parent and child you'll be careful to avoid closing their relevant file descriptor(s).
(However, doing a closing loop like above is poor taste and old fashion)
In general, you'll be careful in your program to set the close-on-exec flag on most file descriptors (e.g. fcntl(2) on F_SETFD operation and FD_CLOEXEC flag, or directly open(2) with O_CLOEXEC), then the execve(2) (done in most child processes after the fork) would close them.

Child Parent Relationship and Inheritance in C

I am totally new with C.
What are the process items that are inherited in a child created using fork();?
What are the process items that are different from the process's parent?
This hasn't got much to do with C, rather with fork(), which is a POSIX system call (and I guess it could behave differently on different systems).
I'd suggest you to read the fork manual, which is really clear about this:
fork() creates a new process by duplicating the calling process. The
new referred to as the child, is an exact duplicate of the calling
process, referred to as the parent, 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)).
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 record locks from its parent (fcntl(2)).
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-2001. 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.
Memory mappings that have been marked with the madvise(2) MADV_DONTFORK flag are not inherited across a fork().
The termination signal of the child is always SIGCHLD (see clone(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.
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 descriptors share open file
status flags, current 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 descriptor in the child
refers to the same open message queue description as the corresponding
descriptor in the parent. This means that the two 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-2001 says that the corresponding
directory streams in the parent and child may share the directory
stream positioning; on Linux/glibc they do not.
If you're interested about Linux, you should also check the clone system call, that lets you specify with more accuracy what you want.
The fork(2) man page on your system (man fork) should give you better details but generally the child only inherits the parent's list of file descriptors, including open files, sockets, and process handles.
From my system's man page (Mac OS X 10.6.6):
The child process has its own copy of the parent's descriptors.
These descriptors reference the same underlying objects, so
that, for instance, file pointers in file objects are shared
between the child and the parent, so that an lseek(2) on a
descriptor in the child process can affect a subsequent read or
write by the parent. This descriptor copying is also used by
the shell to establish standard input and output for newly cre-
ated processes as well as to set up pipes.
See the official description of fork(2)
There is no object-oriented inheritence in C.
Fork'ing in C is basically the process being stopped while it is running, and an entire copy of it being made in (effectively) a different memory space, then both processes being told to continue. They will both continue from where the parent was paused. The only way you can tell which process you are in is to check the return value of the fork() call.
In such a situation the child doesn't really inherit everything from the parent process, it's more like it gets a complete copy of everything the parent had.
The only things of child that are different its parent are its
PPID i.e parent process id and
PID process id.
And when it comes to similarity child process inherits its parent's FILE DESCRIPTOR table thus you would see that always three FILE DESCRIPTORS of child are always occupied which correspond to STDIN,STDOUT and STDERR.

Resources