Hot answers tagged

62

When a process exits, all its children also die (unless you use NOHUP in which case they get back to init). This is wrong. Dead wrong. That person has been lying to you, either when they said that or when they said they knew something about Unix and processes. There are two ways in which the death of a process can indirectly cause the death of its ...


46

The short answer is, fork is in Unix because it was easy to fit into the existing system at the time, and because a predecessor system at Berkeley had used the concept of forks. From The Evolution of the Unix Time-sharing System (relevant text has been highlighted): Process control in its modern form was designed and implemented within a couple of days. ...


44

It's to simplify the interface. The alternative to fork and exec would be something like Windows' CreateProcess function. Notice how many parameters CreateProcess has, and many of them are structs with even more parameters. This is because everything you might want to control about the new process has to be passed to CreateProcess. In fact, CreateProcess ...


24

First of all, every time you execute a command, you shell will fork a new process, regardless of whether you run it with & or not. & only means you're running it in the background. Note this is not very accurate. Some commands, like cd are shell functions and will usually not fork a new process. type cmd will usually tell you whether cmd is an ...


24

fork() was the original UNIX system call. It can only be used to create new processes, not threads. Also, it is portable. In Linux, clone() is a new, versatile system call which can be used to create a new thread of execution. Depending on the options passed, the new thread of execution can adhere to the semantics of a UNIX process, a POSIX thread, ...


23

The traditional way of daemonizing is: fork() setsid() close(0) /* and /dev/null as fd 0, 1 and 2 */ close(1) close(2) fork() This ensures that the process is no longer in the same process group as the terminal and thus won't be killed together with it. The IO redirection is to make output not appear on the terminal.


22

For a daemon, what you want is a process that has no tie to anything. At the very least, you want it to be in its own session, not be attached to a terminal, not have any file descriptor inherited from the parent open to anything, not have a parent caring for you (other than init) have the current directory in / so as not to prevent a umount... To detach ...


22

[I'll repeat part of my answer from here.] Why not just have a command that creates a new process from scratch? Isn't it absurd and inefficient to copy one that is only going to be replaced right away? In fact, that would probably not be as efficient for a few reasons: The "copy" produced by fork() is a bit of an abstraction, since the kernel uses a ...


20

The new process will be created within the fork() call, and will start by returning from it just like the parent. The return value (which you stored in retval) from fork() will be: 0 in the child process The PID of the child in the parent process -1 in the parent if there was a failure (there is no child, naturally) Your testing code works correctly; it ...


20

Man pages are usually terse reference documents. Wikipedia is a better place to turn to for conceptual explanations. Fork duplicates a process: it creates a child process which is almost identical to the parent process (the most obvious difference is that the new process has a different process ID). In particular, fork (conceptually) must copy all the ...


17

The answer is more or less that ls is an external executable. You can see its location by running type -p ls. Why isn't ls built into the shell, then? Well, why should it be? The job of a shell is not to encompass every available command, but to provide an environment capable of running them. Some modern shells have echo, printf, and their ilk as builtins, ...


16

It's not that difficult to decipher in fact. This piece of code just defines a function named : which calls two instances of itself in a pipeline: :|:&. After the definition an instance of this function is started. This leads to a fast increasing number of subshell processes. Unprotected systems (systems without a process number limit per user) will be ...


16

So when a command is fired from a shell, fork() inherits a child process of it and exec() loads the child process to the memory and executes. Not quite. fork() clones the current process, creating an identical child. exec() loads a new program into the current process, replacing the existing one. My qs is: If the child process contains all ...


15

The Linux kernel does implement Copy-on-Write when fork() is called. When the syscall is executed, the pages that the parent and child share are marked read-only. If a write is performed on the read-only page, it is then copied, as the memory is no longer identical between the two processes. Therefore, if only read-operations are being performed, the pages ...


15

WARNING DO NOT ATTEMPT TO RUN THIS ON A PRODUCTION MACHINE. JUST DON'T. Warning: To try any "bombs" make sure ulimit -u is in use. Read below[a]. Let's define a function to get the PID and date (time): bize:~$ d(){ printf '%7s %07d %s\n' "$1" "$BASHPID" "$(date +'%H:%M:%S')"; } A simple, non-issue bomb function for the new user (protect yourself: read [a]...


13

I thought that fork() creates a same process, so I initially that that in that program, the fork() call would be recursively called forever. I guess that new process created from fork() starts after the fork() call? Yes. Let's number the lines: int main (int argc, char **argv) { int retval; /* 1 */ ...


13

You should try setsid(1). Use it like you'd use nohup: setsid command_which_takes_time input > output This (as per the setsid(2) manpage), does a fork(2), an _exit(2) of the parent process, then the child process calls setsid(2) to create a new process group (session). You can't kill that by logging out, and it's not part of the Bash job control ...


13

When a child is forked then it inherits parent's file descriptors, if child closes the file descriptor what will happen ? It inherits a copy of the file descriptor. So closing the descriptor in the child will close it for the child, but not the parent, and vice versa. If child starts writing what shall happen to the file at the parent's end ? Who ...


13

The Bash Reference Manual states: Builtin commands are necessary to implement functionality impossible or inconvenient to obtain with separate utilities. That is, shells are designed to only include built-in commands if: Required by the POSIX standard Commands that require access to the shell itself, such as job control built-ins Commands that are ...


12

Is it ever useful to do nohup ... &? Yes. If you just start a process "in the background" with &, that new process still has membership in the original shell's "process group". If that shell or the process group gets certain signals (SIGHUP, for example), by default they exit. This means that if you run a process with & from a shell started by ...


12

This fork bomb always reminds me of the something an AI programming teacher said on one of the first lessons I attended "To understand recursion, first you must understand recursion". At it's core, this bomb is a recursive function. In essence, you create a function, which calls itself, which calls itself, which calls itself.... until system resources are ...


11

The idea behind threads and processes is about the same: You fork the execution path. Otherwise threads and processes differ in things like memory. I.e. processes have different VM space while threads share whatever existed before the split. Underlying both threading and forking work by using the clone() call (man 2 clone): Unlike fork(2), clone() ...


11

In modern systems none of the memory is actually copied just because a fork system call is used. It is all marked read only in the page table such that on first attempt to write a trap into kernel code will happen. Only once the first process attempt to write will the copying happen. This is known as copy-on-write. However it may be necessary to keep track ...


10

If you send a signal to a process, that process gets killed. I wonder how the rumor that killing a process also kills other processes got started, it seems particularly counter-intuitive. There are, however, ways to kill more than one process. But you won't be sending a signal to one process. You can kill a whole process group by sending a signal to -1234 ...


10

No, fork is not "recursive" in the traditional meaning of recursion. A call to fork() duplicates the current process so it "returns twice". For the child process, the return value is 0, and for the parent the return value is the child PID. fork() does not restart main - that would be more like fork followed by exec. Your program works like this. First ...


10

Ksh93 does a lot to avoid forks. I have no idea how it knows how to handle the first case, as a truss shows that it only calls one write(2) call with the final result. It may be that David scans the command in macro.c and knows that he may handle "echo" internally. What I can say is that I rewrote the parser and the interpreter of the "Bourne Shell" last ...


9

Try creating subshell with (...) : ( command_which_takes_time input > output ) & Example: ~$ ( (sleep 10; date) > /tmp/q ) & [1] 19521 ~$ cat /tmp/q # ENTER ~$ cat /tmp/q # ENTER (...) #AFTER 10 seconds ~$ cat /tmp/q #ENTER Wed Jan 11 01:35:55 CET 2012 [1]+ Done ( ( sleep 10; date ) > /tmp/q )


9

As seen earlier, vfork does not allow the child process to access the parent's memory. exit is a C library function (that's why it's often written as exit(3)). It performs various cleanup tasks such as flushing and closing C streams (the files open through functions declared in stdio.h) and executing user-specified functions registered with atexit. All these ...


9

When a process exits, all its children also die (unless you use NOHUP in which case they get back to init). This is correct if the process is a session leader. When a session leader dies, a SIGHUP is sent to all members of that session. In practice that means its children and their descendants. A process makes itself session leader by calling setsid. ...


8

Yes. Forking is spelled &: echo child & echo parent What may be confusing you is that $$ is not the PID of the shell process, it's the PID of the original shell process. The point of making it this way is that $$ is a unique identifier for a particular instance of the shell script: it doesn't change during the script's execution, and it's ...



Only top voted, non community-wiki answers of a minimum length are eligible