date
int64
1,220B
1,719B
question_description
stringlengths
28
29.9k
accepted_answer
stringlengths
12
26.4k
question_title
stringlengths
14
159
1,637,322,023,000
I need to use a program called Kpax, the "installation" process consist in this: (for bash users, edit ~/.bashrc) export KPAX_ROOT=/home/dritchie/kpax <- substitute the proper pathname here. export PATH=${PATH}:${KPAX_ROOT}/bin I'm using Garuda with fish shell, if I run Kpax using bash works great, the...
In fish shell 3.2 or later, you can just run: fish_add_path /home/dritchie/kpax/bin substituting in your home directory. You can run this once at the command line, or add it to ~/.config/fish/config.fish; either way it will be remembered. Here's documentation for fish_add_path. You might still need the KPAX_ROOT envi...
Environment variables in Fish
1,637,322,023,000
I'm trying to run a simple command on my fish shell, but I am not able to execute. It just keeps adding lines for me to add additional data to, not sure on how to execute accordingly. $ for acc in `cat uniprot_ids.txt` ; do curl -s "https://www.uniprot.org/uniprot/$acc.fasta" ; done > uniprot_seqs.fasta
Fish is not bash compatible, but uses its own scripting language. In this case the only differences are it doesn't support backticks (```), instead it uses parentheses. for-loops don't use do/done, instead they just end in "end" for acc in (cat uniprot_ids.txt); curl -s "https://www.uniprot.org/uniprot/$acc.fasta" ;...
run for loop with bash command in fish shell
1,637,322,023,000
I am building a script that should work in csh, bash, and fish with no change: This does the right thing in all the shells, perl -e '$bash=shift;$csh=shift;for(@ARGV){unlink;rmdir;}if($bash=~s/h//){exit$bash;}exit$csh;' "$?h" "$status" $PARALLEL_TMP ...
$ bash -c 'false; echo "[$status]" "[`echo \$?h`]"' [] [1h] $ csh -c 'false; echo "[$status]" "[`echo \$?h`]"' [1] [0] $ fish -c 'false; echo "[$status]" "[`echo \$?h`]"' [1] [`echo $?h`] Uses the fact that ` is not special in fish, and that Bourne-like shells do an extra level of backslash processing within `...`. Y...
Stop fish complaining: fish: $? is not the exit status. In fish, please use $status
1,637,322,023,000
I have been using fish shell for a while, but only recently got into playing around with the oh-my-fish framework and theming the prompt. I cannot figure out what this [I] character means! In most themes I install it comes at the very beginning of the prompt, but depending it can be elsewhere. In my fish_prompt.fish ...
The [I] signifies "Vi Insert Mode" when the shell is in Vi command line editing mode. This changes to [N] when you press Esc to enter "Vi Normal Mode" (also sometimes referred to as "Vi Command Mode"). The solution (to remove the [I]) is to use function fish_mode_prompt end in your fish configuration file.
Terminal prompts have a mysterious [I] in it
1,637,322,023,000
Fish is not recognizing the abbr command. fish: Unknown command “abbr” abbr: command not found In all other ways fish is behaving normally. The Fish documentation doesn't give any clues as to why this might happen. Stack: EC2 Ubuntu machine, fish version 2.0.0.
abbr was not in 2.0.0 - it was only added in 2.2.0, so that's why it isn't working! You can install the latest available packages (currently 2.2.0, soon to be 2.3.0) from the fish-shell Ubuntu PPA.
fish: Unknown command "abbr"
1,402,510,190,000
While I am connecting to my server I get, -bash: fork: retry: Resource temporarily unavailable -bash: fork: retry: Resource temporarily unavailable -bash: fork: retry: Resource temporarily unavailable -bash: fork: retry: Resource temporarily unavailable -bash: fork: Resource temporarily unavailable And I try followin...
This could be due to some resource limit, either on the server itself (or) specific to your user account. Limits in your shell could be checked via ulimit -a. Esp check for ulimit -u max user processes, if you have reached max processes, fork is unable to create any new and failing with that error. This could also be ...
fork: retry: Resource temporarily unavailable
1,402,510,190,000
Recently I've been digging up information about processes in GNU/Linux and I met the infamous fork bomb : :(){ : | :& }; : Theoretically, it is supposed to duplicate itself infinitely until the system runs out of resources... However, I've tried testing both on a CLI Debian and a GUI Mint distro, and it doesn't seem ...
You probably have a Linux distro that uses systemd. Systemd creates a cgroup for each user, and all processes of a user belong to the same cgroup. Cgroups is a Linux mechanism to set limits on system resources like max number of processes, CPU cycles, RAM usage, etc. This is a different, more modern, layer of resource...
Why can't I crash my system with a fork bomb?
1,402,510,190,000
I am running a docker server on Arch Linux (kernel 4.3.3-2) with several containers. Since my last reboot, both the docker server and random programs within the containers crash with a message about not being able to create a thread, or (less often) to fork. The specific error message is different depending on the pro...
The problem is caused by the TasksMax systemd attribute. It was introduced in systemd 228 and makes use of the cgroups pid subsystem, which was introduced in the linux kernel 4.3. A task limit of 512 is thus enabled in systemd if kernel 4.3 or newer is running. The feature is announced here and was introduced in this ...
Creating threads fails with “Resource temporarily unavailable” with 4.3 kernel
1,402,510,190,000
In Program 1 Hello world gets printed just once, but when I remove \n and run it (Program 2), the output gets printed 8 times. Can someone please explain me the significance of \n here and how it affects the fork()? Program 1 #include <sys/types.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> int main...
When outputting to standard output using the C library's printf() function, the output is usually buffered. The buffer is not flushed until you output a newline, call fflush(stdout) or exit the program (not through calling _exit() though). The standard output stream is by default line-buffered in this way when it's ...
Why does a program with fork() sometimes print its output multiple times?
1,402,510,190,000
What are the practical differences from a sysadmin point of view when deploying services on a unix based system?
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....
What's the difference between running a program as a daemon and forking it into background with '&'?
1,402,510,190,000
I have been studying the Linux kernel behaviour for quite some time now, and it's always been clear to me that: When a process dies, all its children are given back to the init process (PID 1) until they eventually die. However, recently, someone with much more experience than me with the kernel told me that: When ...
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. The person saying that was either mistaken, or confused a particular situation with the the general case. There are two ways in which the death of a process can indirectly cause the ...
Is there any UNIX variant on which a child process dies with its parent?
1,402,510,190,000
The UNIX system call for process creation, fork(), creates a child process by copying the parent process. My understanding is that this is almost always followed by a call to exec() to replace the child process' memory space (including text segment). Copying the parent's memory space in fork() always seemed wasteful...
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 ...
Why is the default process creation mechanism fork?
1,402,510,190,000
I have some confusion regarding fork and clone. I have seen that: fork is for processes and clone is for threads fork just calls clone, clone is used for all processes and threads Are either of these accurate? What is the distinction between these 2 syscalls with a 2.6 Linux kernel?
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 ...
Fork vs Clone on 2.6 Kernel Linux
1,402,510,190,000
A fork() system call clones a child process from the running process. The two processes are identical except for their PID. Naturally, if the processes are just reading from their heaps rather than writing to it, copying the heap would be a huge waste of memory. Is the entire process heap copied? Is it optimized in a ...
The entirety of fork() is implemented using mmap / copy on write. This not only affects the heap, but also shared libraries, stack, BSS areas. Which, incidentally, means that fork is a extremely lightweight operation, until the resulting 2 processes (parent and child) actually start writing to memory ranges. This fe...
Does fork() immediately copy the entire process heap in Linux?
1,402,510,190,000
When a child is forked then it inherits parent's file descriptors, if child closes the file descriptor what will happen? If child starts writing what shall happen to the file at the parent's end? Who manages these inconsistencies, kernel or user? When a process calls the close function to close a particular file throu...
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 t...
File descriptor and fork
1,402,510,190,000
First this question is related but definitely not the same as this very nice question: Difference between nohup, disown and & I want to understand something: when I do '&', I'm forking right? Is it ever useful to do "nohup ... &" or is simply & sufficient? Could someone show a case where you'd be using '&' and still w...
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 ...
When do you need 'nohup' if you're already forking using '&'?
1,402,510,190,000
According to Wikipedia (which could be wrong) When a fork() system call is issued, a copy of all the pages corresponding to the parent process is created, loaded into a separate memory location by the OS for the child process. But this is not needed in certain cases. Consider the case when a child executes an "exec" ...
Nothing particular happens. All processes are sharing the same set of pages and each one gets its own private copy when it wants to modify a page.
How does copy-on-write in fork() handle multiple fork?
1,402,510,190,000
I'm trying to learn UNIX programming and came across a question regarding fork(). I understand that fork() creates an identical process of the currently running process, but where does it start? For example, if I have code int main (int argc, char **argv) { int retval; printf ("This is most definitely the pare...
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) ...
After fork(), where does the child begin its execution?
1,402,510,190,000
WARNING DO NOT ATTEMPT TO RUN THIS ON A PRODUCTION MACHINE In reading the Wikipedia page on the topic I generally follow what's going on with the following code: :(){ :|:& };: excerpt of description The following fork bomb was presented as art in 2002;56 its exact origin is unknown, but it existed on Usenet prio...
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 call...
How does a fork bomb work?
1,402,510,190,000
I don't have much experience, just trying to get involved into the processes how do they interpret to hardware from user level. 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. If the child process contains all the attributes...
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...
How do fork and exec work?
1,402,510,190,000
Passing a password on command line (to a child process started from my program) is known to be insecure (because it can be seen even by other users with ps command). Is it OK to pass it as an environment variable instead? What else can I use to pass it? (Except of environment variable) the easiest solution seems to us...
Process arguments are visible to all users, but the environment is only visible to the same user (at least on Linux, and I think on every modern unix variant). So passing a password through an environment variable is safe. If someone can read your environment variables, they can execute processes as you, so it's game ...
How to pass a password to a child process?
1,402,510,190,000
I program that I wrote in C fork()'s off a child process. Neither process will terminate. If I launch the program from the command line and press control-c which process(es) will receive the interrupt signal?
Why don't we try it out and see? Here's a trivial program using signal(3) to trap SIGINT in both the parent and child process and print out a message identifying the process when it arrives. #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <signal.h> void parent_trap(int sig) {fprintf(stderr, "They ...
fork() and how signals are delivered to processes
1,402,510,190,000
I've written quite a few shell scripts over the years (but I'm certainly not a sysadmin) and there's something that always caused me troubles: how can I fork a shell command immune to hangups in the background from a Bash script? For example if I have this: command_which_takes_time input > output How can I "nohup" an...
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 )
How to totally fork a shell command that is using redirection
1,402,510,190,000
I found the following function in the source code of catwm (a minimalistic window manager): void spawn(const Arg arg) { if(fork() == 0) { if(fork() == 0) { if(dis) close(ConnectionNumber(dis)); setsid(); execvp((char*)arg.com[0],(char**)arg.com); ...
The following paragraphs, quoted from Stevens and Rago Advanced Programming in the UNIX Environment, describe two of six coding rules for writing a daemon. Specifically, they implement them in a single daemonize function listed in Figure 13.1 in case you want to look it up. Call fork and have the parent exit. This d...
Double fork() - why?
1,402,510,190,000
After going through the famous Fork Bomb questions on Askubuntu and many other Stack Exchange sites, I don't quite understand what everyone is saying like it's obvious. Many answers (Best example) say this: "{:|: &} means run the function : and send its output to the : function again " Well, what exactly is the outp...
Piping doesn't require that the first instance finishes before the other one starts. Actually, all it is really doing is redirecting the stdout of the first instance to the stdin of the second one, so they can be running simultaneously (as they have to for the fork bomb to work). Well, What exactly is the output of :...
How exactly does the typical shell "fork bomb" call itself twice?
1,402,510,190,000
I get how a normal fork bomb works, but I don't really understand why the & at the end of the common bash fork bomb is required and why these scripts behave differently: :(){ (:) | (:) }; : and :(){ : | :& }; : The former causes a cpu usage spike before throwing me back to the login screen. The latter instead just ...
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 t...
Why do these bash fork bombs work differently and what is the significance of & in it?
1,402,510,190,000
On his web page about the self-pipe trick, Dan Bernstein explains a race condition with select() and signals, offers a workaround and concludes that Of course, the Right Thing would be to have fork() return a file descriptor, not a process ID. What does he mean by this -- is it something about being able to select(...
The problem is described there in your source, select() should be interrupted by signals like SIGCHLD, but in some cases it doesn't work that well. So the workaround is to have signal write to a pipe, which is then watched by select(). Watching file descriptors is what select() is for, so that works around the problem...
Why should fork() have been designed to return a file descriptor?
1,402,510,190,000
I want to write my own systemd unit files to manage really long running commands1 (in the order of hours). While looking the ArchWiki article on systemd, it says the following regarding choosing a start up type: Type=simple (default): systemd considers the service to be started up immediately. The process must not fo...
The service is allowed to call the fork system call. Systemd won't prevent it, or even notice if it does. This sentence is referring specifically to the practice of forking at the beginning of a daemon to isolate the daemon from its parent process. “The process must not fork [and exit the parent while running the serv...
Why "the process must not fork" for simple type services in systemd?
1,402,510,190,000
The standard way of making new processes in Linux is that the memory footprint of the parent process is copied and that becomes the environment of the child process until execv is called. What memory footprint are we talking about, the virtual (what the process requested) or the resident one (what is actually being us...
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. Ho...
When a process forks is its virtual or resident memory copied?
1,402,510,190,000
Why does ls require a separate process for its execution? I know the reason why commands like cd can't be executed by forking mechanism but is there any harm if ls is executed without forking?
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 e...
Why does "ls" require a separate process for executing?
1,402,510,190,000
I would like to understand in detail the difference between fork() and vfork(). I was not able to digest the man page completely. I would also like to clarify one of my colleagues comment "In current Linux, there is no vfork(), even if you call it, it will internally call fork()."
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, for...
What's the difference between fork() and vfork()?
1,402,510,190,000
From the man page of vfork(): vfork() differs from fork() in that the parent is suspended until the child makes a call to execve(2) or _exit(2). The child shares all memory with its parent, including the stack, until execve() is issued by the child. The child must not return from the current function ...
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 fu...
Why should a child of a vfork or fork call _exit() instead of exit()?
1,402,510,190,000
So I can run a process in Unix / Linux using POSIX, but is there some way I can store / redirect both the STDOUT and STDERR of the process to a file? The spawn.h header contains a deceleration of posix_spawn_file_actions_adddup2 which looks relevant, but I'm not sure quite how to use it. The process spawn: posix_spawn...
Here's a minimal example of modifying file descriptors of a spawned process, saved as foo.c: #include <stdio.h> #include <stdlib.h> #include <sys/stat.h> #include <fcntl.h> #include <spawn.h> int main(int argc, char* argv[], char *env[]) { int ret; pid_t child_pid; posix_spawn_file_actions_t child_fd_acti...
Get output of `posix_spawn`
1,402,510,190,000
I'm learning about fork() and exec() commands. It seems like fork() and exec() are usually called together. (fork() creates a new child process, and exec() replaces the current process image with a new one.) However, in what scenarios might you call each function on its own? Are there scenarios like these?
Sure! A common pattern in "wrapper" programs is to do various things and then replace itself with some other program with only an exec call (no fork) #!/bin/sh export BLAH_API_KEY=blub ... exec /the/thus/wrapped/program "$@" A real-life example of this is GIT_SSH (though git(1) does also offer GIT_SSH_COMMAND if you ...
When to call fork() and exec() by themselves?
1,402,510,190,000
When you fork a process, the child inherits its parent's file descriptors. I understand that when this happens, the child receives a copy of the parent's file descriptor table with the pointers in each pointing to the same open file description. Is this the same thing as a file table, as in http://en.wikipedia.org/wik...
I found the answer in documentation for the open system call: The term open file description is the one used by POSIX to refer to the entries in the system-wide table of open files. In other contexts, this object is variously also called an "open file object", a "file handle", an "open file table entry", or—in kernel...
What is an open file description?
1,402,510,190,000
I have two bash scripts that try to check hosts that are up: Script 1: #!/bin/bash for ip in {1..254}; do ping -c 1 192.168.1.$ip | grep "bytes from" | cut -d" " -f 4 | cut -d ":" -f 1 & done Script 2: #!/bin/bash for ip in {1..254}; do host=192.168.1.$ip (ping -c 1 $host > /dev/null if [ "$?" = 0 ...
There is already an answer which gives an improved code snippet to the task the original poster questions was related to, while it might not yet have more directly responded to the question. The question is about differences of A) Backgrounding a "command" directly, vs B) Putting a subshell into the background (i.e ...
Putting subshell in background vs putting command in background
1,402,510,190,000
In this page from The Design and Implementation of the 4.4BSD Operating System, it is said that: A major difference between pipes and sockets is that pipes require a common parent process to set up the communications channel However, if I record correctly, the only way to create a new process is to fork an existin...
Am I then right to think that any pair of processes can be piped to each other? Not really. The pipes need to be set up by the parent process before the child or children are forked. Once the child process is forked, its file descriptors cannot be manipulated "from the outside" (ignoring things like debuggers), the ...
Can I pipe any two processes to each other?
1,402,510,190,000
I'm studying 'operation system concepts' on my own and I'm studying the chp3. process part. There is an example where the 'fork()' function is called and depending of the returned pid value like the following: pid=fork(); if(pid<0){ //error stuff } else if(pid==0){ // child process stuff } else{ // parent process stuf...
Yes, you are correct. In particular, this means that the child will inherit all variables from the parent process with the value they had at the moment of the fork. However, if at a later step one of the parent or the child modifies one of these variables, the modification will be local to this process: if the child m...
what does it mean 'fork()' will copy address space of original process
1,402,510,190,000
I just learned about a fork bomb, an interesting type of a denial of service attack. Wikipedia (and a few other places) suggest using :(){ :|:& };: on UNIX machines to fork the process an infine number of times. However, it doesn't seem to work on Mac OS X Lion (I remember reading that the most popular operating syste...
How a fork bomb works: in C (or C-like) code, a function named fork() gets called. This causes linux or Unix or Unix-a-likes to create an entirely new process. This process has an address space, a process ID, a signal mask, open file descriptors, all manner of things that take up space in the OS kernel's somewhat limi...
Fork bomb on a Mac?
1,402,510,190,000
This post is basically a follow-up to an earlier question of mine. From the answer to that question I realized that not only I don't quite understand the whole concept of a "subshell", but more generally, I don't understand the relationship between fork-ing and children processes. I used to think that when process X e...
Since, according to zshall(1), $ZDOTDIR/.zshenv gets sourced whenever a new instance of zsh starts If you focus on the word "starts" here you'll have a better time of things. The effect of fork() is to create another process that begins from exactly where the current process already is. It's cloning an existing proc...
On `fork`, children processes, and "subshells"
1,402,510,190,000
I have a runscript that starts some processes and sends them to the background mongod & pid_mongo=$! redis-server & pid_redis=$! # etc. All these processes then output concurrently to the same standard output. My question: is it possible to color the output of each different forked process, so that - for exampl...
You could do this by piping through a filter, it is just a matter of adding appropriate ANSI codes before and after each line: http://en.wikipedia.org/wiki/ANSI_escape_sequences#Colors I could not find a tool which actually does this after a few minutes googling, which is bit odd considering how easy it would be to wr...
Coloring output of forked processes
1,402,510,190,000
When we fork() a process, the child process inherits the file descriptors. The question is, why? As I am seeing it, sharing the file descriptor is a headache when every process is trying to keep track of where the r/w pointer is. Why was this design decision taken?
POSIX explains the reasoning thus: There are two reasons why POSIX programmers call fork(). One reason is to create a new thread of control within the same program (which was originally only possible in POSIX by creating a new process); the other is to create a new process running a different program. In the latter c...
Why are file descriptors shared between forked processes?
1,402,510,190,000
On a Linux system a C process is started on boot, which creates a fork of itself. It is not a kernal process or something. In most cases a ps -ef show both processes as expecxted, but sometimes it looks like the following: 1258 root 0:00 myproc 1259 root 0:00 [myproc] i.e. one of the processes surround...
ps -f normally shows the argument list passed to the last execve() system call the process or any of its ancestors did. When you run a command xxx arg1 arg2 at a shell prompt, your shell usually forks a process searches for a command by the xxx name and executes it as: execve("/path/to/that/xxx", ["xxx", "arg1", "arg2...
Why do forked processes sometimes appear with brackets [] around their name in ps? [duplicate]
1,402,510,190,000
If I have a Bash script like: function repeat { while :; do echo repeating; sleep 1 done } repeat & echo running once running once is printed once but repeat's fork lives forever, printing endlessly. How should I prevent repeat from continuing to run after the script which created it has exited? I th...
This kills the background process before the script exits: trap '[ "$pid" ] && kill "$pid"' EXIT function repeat { while :; do echo repeating; sleep 1 done } repeat & pid=$! echo running once How it works trap '[ "$pid" ] && kill "$pid"' EXIT This creates a trap. Whenever the script is about to exi...
Prevent a shell fork from living longer than its initiator?
1,402,510,190,000
My nginx unitfile is following, [root@arif ~]# cat /usr/lib/systemd/system/nginx.service [Unit] Description=The nginx HTTP and reverse proxy server After=network.target remote-fs.target nss-lookup.target [Service] Type=forking PIDFile=/run/nginx.pid # Nginx will fail to start if /run/nginx.pid already exists but has ...
Why a service does that? Services generally do not do that, in fact. Aside from the fact that it isn't good practice, and the idea of "dæmonization" is indeed fallacious, what services do isn't what the forking protocol requires. They get the protocol wrong, because they are in fact doing something else, which is ...
Why forking is used in a unit file of a service?
1,402,510,190,000
Recently I got an load-too-high issue on our server. I watched top for like half an hour to find out that it was Nagios that forked a lot of short-lived processes. After bouncing Nagios, everything was back to normal. My question here is, how to find out the root process that forks a lot like this more quickly? Thanks...
If you run an OS that supports dtrace, this script will help you identifying what processes are launching short lived processes: #!/usr/sbin/dtrace -qs proc:::exec { self->parent=stringof((unsigned char*)curpsinfo->pr_psargs); } proc:::exec-success /self->parent != NULL/ { printf("%s -> %s\n",self->parent,curpsi...
How to find out the process(es) that forks a lot?
1,402,510,190,000
I have read the other questions about its functionality -- that fork bombs operate both by consuming CPU time in the process of forking, and by saturating the operating system's process table. A basic implementation of a fork bomb is an infinite loop that repeatedly launches the same processes. But I really want to kn...
It is not something new. It dates way back to 1970's when it got introduced. Quoting from here, One of the earliest accounts of a fork bomb was at the University of Washington on a Burroughs 5500 in 1969. It is described as a "hack" named RABBITS that would make two copies of itself when it was run, and these two wou...
What's the history behind the fork bomb?
1,402,510,190,000
When running the fork call to create a new process, if it succeed it returns either 0 (the child) or the parent. I didn't get the idea behind this. Why doesn't fork just always return child or always parent?
When you fork(), the code that’s running finds itself running in two processes (assuming the fork is successful): one process is the parent, the other the child. fork() returns 0 in the child process, and the child pid in the parent process: it’s entirely deterministic. This is how you can determine, after the fork(),...
Why does fork sometimes return parent and sometimes child?
1,402,510,190,000
Anyone understand the following code , running in bash ? :(){ :|:& };: It seems to be a "fork" bomb on Linux.
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 pro...
Why is the following command killing a system?
1,354,215,010,000
From the fork(2) man page: RETURN VALUE On success, the PID of the child process is returned in the parent, and 0 is returned in the child. On failure, -1 is returned in the parent, no child process is created, and errno is set appropriately. I am wondering about the reasons that would make a fork call fai...
In the C API, system calls return a negative value to indicate an error, and the error code in errno gives more information on the nature of the error. Your man page should explain the possible errors on your system. There are two standard error codes: EAGAIN indicates that the new process cannot be created due to a ...
Fork: Negative return value
1,354,215,010,000
As when we do fork on current process, our process as parent process generates child process with same characteristics but different process IDs. So after that, when we do exec() in our child process, process stops execution, and our program which was executing in our stoppped child process, now has his own process. I...
Yes, because that's how it's done in UNIX. There is no "run application" system call; it's always done by fork/exec pairs. Incidentally, exec does not generate a new PID. exec replaces the contents of the process -- the memory is discarded, and a whole new executable is loaded -- but the kernel state remains the same ...
fork() and exec() confusion
1,354,215,010,000
I need to figure out how many forks are done and how many concurrent processes are run by each user over time. It does not look like this information is tracked by my distribution. I know how to sets limits, but I'm interested in tracking these numbers for each user.
Try the psacct package (GNU accounting), it should do just about everything you need, once installed and enabled (accton), then lastcomm will keep report on user processes (see also sa and dump-acct). See this for reference: User's executed commands log file You might need to upgrade the version to log PID/PPID, see h...
How to track the number of processes and forks per user?
1,354,215,010,000
Following a fork() call in Linux, two processes (one being a child of the other) will share allocated heap memory. These allocated pages are marked COW (copy-on-write) and will remain shared until either process modifies them. At this point, they are copied, but the virtual address pointers referencing them remain the...
One of the things the kernel does during a context switch between processes is to modify the MMU tables to remove entries that describe the previous process's address space and add entries that describe the next process's address space. Depending on the processor architecture, the kernel and possibly the configuration...
How can two identical virtual addresses point to different physical addresses?
1,354,215,010,000
I'm currently developping a systemd daemon. The problem I'm facing is that the daemon is killed 1m30s after beeing launched because the forking is not detected. I'm using the int daemon(int nochdir, int noclose) function to daemonize the process. int main() { openlog("shutdownd", LOG_PID, LOG_DAEMON); if(daem...
Do not do that. At all. Any of it, either through a library function or rolling your own code. For any service management system. It has been a wrongheaded idea since the 1990s. Your dæmon is already running in a service context, invoked that way by a service manager. Your program should do nothing in this respect...
Systemd timeout because it doesn't detect daemon forking
1,354,215,010,000
I've a very specific question about fork system call. I've this piece of code: int main (void) { for (int i = 0; i < 10; i++) { pid_t pid = fork (); if ( !pid ) { printf("CHILD | PID: %d, PPID: %d\n", getpid(), getppid()); _exit(i + 1); } } for (int i = 0...
When you fork, the kernel creates a new process which is a copy of the forking process, and both processes continue executing after the fork (with the return code showing whether an error occurred, and whether the running code is the parent or the child). This “continue executing” part doesn’t necessarily happen strai...
How does fork system call really works
1,354,215,010,000
I have a socket server running and listening for incoming connections on a non-admin port (i.e. > 1024). I would also like for this process to be able to handle another type of connection on a different port for monitoring purposes. I have found questions on SE for the opposite situation, many-to-one but this would be...
Absolutely possible You can use a selector or poll to receive notifications and manage each connection. http://linux.die.net/man/2/select
Bind one process to multiple ports?
1,354,215,010,000
If we look at the example #include <stdio.h> #include <unistd.h> void main(){ int pi_d ; int pid ; pi_d = fork(); if(pi_d == 0){ printf("Child Process B:\npid :%d\nppid:%d\n",getpid(),getppid()); } if(pi_d > 0){ pid = fork(); if(pid > 0){ printf("\nParent Process:\npid:%d\nppid :%d\n",ge...
Quoting from POSIX fork definition (bold emphasis mine): RETURN VALUE Upon successful completion, fork() shall return 0 to the child process and shall return the process ID of the child process to the parent process. Both processes shall continue to execute from the fork() function. Otherwise, -1 shall be returned to...
How does the fork system call work?
1,354,215,010,000
Unfortunately I've had no luck figuring this out, as everything I find is just on the syntax of redirection, or shallow information about how redirection works. What I want to know is how bash actually changes stdin/stdout/stderr when you use pipes or redirection. If for example, you execute: ls -la > diroutput.log H...
I was able to figure it out using strace -f and writing a small proof of concept in C. It appears that bash just manipulates file descriptors in the child process before calling execve as I thought. Here's how ls -la > diroutput.log works (roughly): bash calls fork(2) forked bash process sees the output redirection a...
How does bash actually change stdin/stdout/stderr when using redirection/piping
1,354,215,010,000
If a program runs fork() what sets standard streams STDOUT, STDIN and STDERR?
Stdin, stdout and stderr are inherited from the parent process. It's up to the child process to change them to point to new files if that is needed. From the fork(2) man page: * The child inherits copies of the parent's set of open file descrip‐ tors. Each file descriptor in the child refers to the sam...
What sets a child's STDERR, STDOUT, and STDIN?
1,354,215,010,000
In the man page for ps, it lists process flag 1 as "process forked but didn't exec". What would be a common use case/situation for a process to be in this state?
This sentence refers to the fork and exec system calls¹. The fork system call creates a new process by duplicating the calling process: after running fork, there are two processes which each have their own memory¹ with initially-identical content except for the return value of the fork system call, the process ID and ...
Process Flag 1: Forked but didn't exec (use case?)
1,354,215,010,000
When executing ps command in my Linux system i see some user processes twice (different PID...). I wonder if they are new processes or threads of the same process. I know some functions in standard C library that could create a new process such fork(). I wonder what concrete functions can make a process appear twice w...
Little bit confusing. fork is a system call which creates a new process by copying the parent process' image. After that if child process wants to be another program, it calls some of the exec family system calls, such as execl. If you for example want to run ls in shell, shell forks new child process which then calls...
Which system calls could create a new process?
1,354,215,010,000
This is the code example given: # include <stdio.h> # include <unistd.h> void main() { static char *mesg[] = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"}; int display(char *), i; for (i=0; i<10; ++i) display(mesg[i]); sleep(2); } int display(char *m) { char err_msg[25]; switch (fork()) { case 0:...
The child processes start running as soon as you fork(), in fact they do not even "start", they just continue in the code after the fork() invocation, just like the parent does. Only the return value of fork() is different. Parent and child can exit in either order. So yes, context switching will make all the processe...
Why does a "child" process finish before its parent?
1,354,215,010,000
I am running R job under a normal user john and root. Interestingly, the program stalls under john user but runs quickly under root. Using strace, I found that when john runs the R, the process stalls for its child process. I guess the linux do not let the child process continue and the parent (main program) stays sta...
Use strace -f R to follow R and all its child processes as well. This should show the exact point where the child program hangs. Some additional possible points to check: as root (su - root), and as the user john, compare the outputs of: ulimit -a #will show all the "limits" set for that user. You may reach one of th...
Program stall under user but runs under root
1,354,215,010,000
It is well-known that if I add myself to a new group, that change will not be reflected until I log out and back in: $ sudo adduser me newgroup $ groups me sudo $ groups me me sudo newgroup $ This odd behavior is because groups is interpreted by the shell and new group membership is not shown. But groups me actually...
Groups are inherited by a process from its parent. Bash has no choice in the matter. A process running as root can obtain new supplementary groups upon request; a process not running as root can only relinquish supplementary groups. The command groups with no arguments returns its own list of groups (which is inherite...
How does bash pass user groups to a child?
1,354,215,010,000
I was looking at the output of pstree, and realised that processes that I started using dmenu seem to fork from bash. What is the reasoning behind this? And is there any way I can make dmenu behave like gmrun and other application launchers and only launch the process? EDIT: The dmenu manpage says that the shell exe...
I ended up asking about it on the ArchLinux forum after a little while. Here is what /usr/bin/dmenu_run should look like: #!/bin/sh cachedir=${XDG_CACHE_HOME:-"$HOME/.cache"} if [ -d "$cachedir" ]; then cache=$cachedir/dmenu_run else cache=$HOME/.dmenu_cache # if no xdg dir, fall back to dotfile in ~ fi exec $...
Dmenu Processes Forked by Bash?
1,354,215,010,000
As far as I know, when vfork is called, the child process uses the same address space as that of the parent and any changes made by the child process in parent'ss variables are reflected onto the parent process. My questions are: When a child process is spawned, is the parent process suspended? If yes, why? They can...
Your question is partly based on bad naming convention. A "thread of control" in kernel-speak is a process in user-speak. So when you read that vfork "the calling thread is suspended" think "process" (or "heavyweight thread" if you like) not "thread" as in "multi-threaded process". So yes, the parent process is suspe...
When vfork is called is parent process really suspended?
1,354,215,010,000
GDB seems to hang everytime when I try run command from gdb prompt. When I ran ps, there are two gdb processes that have been spawned and pstack reveals the following - 15:47:02:/home/stufs1/pmanjunath/a2/Asgn2_code$ uname -a SunOS compserv1 5.10 Generic_118833-24 sun4u sparc SUNW,Sun-Blade-1500 15:44:04:/home/stufs...
The process that calls vfork() hangs because it is the vfork() parent and the child did borrow the process image at that time so it cannot run until the child finishes a call to_exit() or exec*(). So you need to find out why the exec*() hangs. A typical reason for a hang in exec*() is a NFS hang or a traversal through...
GDB hangs forever on Solaris
1,354,215,010,000
strace runs a specified command until it exits. It intercepts and records the system calls which are called by a process and the signals which are received by a process. When running an external command in a bash shell, the shell first fork() a child process, and then execve() the command in the child process. So I...
$ strace -f time execve("/usr/bin/time", ["time"], [/* 66 vars */]) = 0 brk(0) = 0x84c000 ... Strace directly invokes the program to be traced. It doesn't use the shell to run child commands, unless the child command is a shell invocation. The approximate sequence of events here is as...
Why doesn't strace report that the parent shell fork() a child process before execve() a command?
1,354,215,010,000
There are a couple of questions related to the fork bomb for bash :(){ :|: & };: , but when I checked the answers I still could not figure out what the exactly the part of the bomb is doing when the one function pipes into the next, basically this part: :|: . I understand so far, that the pipe symbol connects two com...
Short answer: nothing. If a process takes in nothing on STDIN, you can still pipe to it. Simiarly, you can still pipe from a process that produces nothing on STDOUT. Effectively, you're simply piping a single EOF indicator in to the second process, that is simply ignored. The construction using the pipe is simply a va...
What exactly is the function piping into the other function in this fork bomb :(){ :|: & };:?
1,354,215,010,000
We have a spark cluster that launches via supervisor. Excerpts: /etc/supervisor/conf.d/spark_master.conf: command=./sbin/start-master.sh directory=/opt/spark-1.4.1 /etc/supervisor/conf.d/spark_worker.conf: command=./sbin/start-slave.sh spark://spark-master:7077 directory=/opt/spark-1.4.1 The challenge for superviso...
Solution I inferred from a previous version of the documentation: /etc/supervisor/conf.d/spark_master.conf: command=/opt/spark-1.4.1/bin/spark-class org.apache.spark.deploy.master.Master directory=/opt/spark-1.4.1 /etc/supervisor/conf.d/spark_worker.conf: command=/opt/spark-1.4.1/bin/spark-class org.apache.spark.depl...
Launch Spark in Foreground via Supervisor
1,354,215,010,000
My code is forking a process and printing each process' PID and PPID. I was expecting the child's PPID to be same as the parent's PID, but it is not coming up as such. I'm using Ubuntu 14.04. #include <stdio.h> #include <sys/wait.h> int main(){ int pid; pid = fork(); if(pid==0){ printf("\nI am the...
My guess is: the parent returned before the child, which became an orphan. PID 1135 must be your user init process, which became the process' new parent. (there are 2 subreapers in a Ubuntu user session). $ ps -ef | grep init you 1135 ... init --user If you want your parent to wait for its child, use wait. Y...
Unexpected parent process id in output
1,354,215,010,000
I am doing some experiments to know how environment variables are inherited from parent process to child process by executing shell scripts in zsh and then use pstree <username> to see the inheritance tree. I suppose that zsh do a fork to run a script. But the process name in the pstree is the script file name not zsh...
A program can change it's own command line (as shown in ps's CMD column, or pstree). That's what zsh is doing—it's changing its command name to the shell script, presumably to make it easier to tell what each zsh is doing when looking at ps. For example (though I'm using bash, not zsh, but the same works in zsh—I test...
shell script process fork
1,354,215,010,000
Basic concurrent client/server architecture: There's a main loop listening for requests on a port (for example 3000), after accepting the connection the server spawns a child process that ends up having access to file descriptors where data can be read. If we have multiple clients connected to the server, the server w...
A TCP/IP connection has both a source port and a destination port, so if the same server connects to another server on port 3000 multiple times, the Linux kernel can sort out the connections because each one has a unique IP + source port + destination port. This can be seen with the output of netstat when there are ...
How does the kernel know which file descriptor to write data to after fork() in a concurrent server?
1,354,215,010,000
In Linux (CentOS 7.5, kernel 3.10, gcc 7.3), is it possible to change the working directory of a child process created by posix_spawn before it runs a given process image (an executable)? If yes, how? If no, what is the best practice to do it?
There is no way to do thisas part of the posix_spawn() set of functions. There is an ongoing discussion initiated by redhat whether such a feature should be added. If this gets accepted, it could become part of POSIX in the next version - this may be in 2-3 years. BTW: posix_spawn() is implemented on top of vfork()/ex...
How to change working directory of a child process by posix_spawn? [closed]
1,354,215,010,000
Consider a parent process which completes a socket/bind/accept, and will fork children with that socket open for them to communicate with, while the parent continues accepting connections. That parent process is then killed. Another process now attempts to bind to the same address the parent process was bound to, on...
While I don't understand all of the semantics (I'm either looking in the wrong place, or the documentation is lacking), I believe that for a certain amount of time after closing a connection (perhaps set by SO_LINGER), no process can open a new socket with the same details unless they have SO_REUSEADDR set. This is to...
What are the semantics of getting a EADDRINUSE when no listening socket is bound, but connections are open
1,354,215,010,000
I'm trying to run a simple one file C program in a Virtual Machine. In fact it is the fork bomb c program: #include <stdio.h> #include <sys/types.h> int main() { while(1) { fork(); } return 0; } I want to do this in order to check how much of an effect this VM would have on another VMs ru...
With qemu kvm, booting the host kernel in a headless VM with console I/O on serial (redirected to the terminal you run it from): Compile that fork-bomb.c into a static init executable: gcc -static -o init fork-bomb.c Make an initramfs with just that init at the root: bsdtar --format newc -cf initrd init Boot the ...
What is the easiest way to run a VM that executes a simple C program
1,642,817,338,000
Let's say, we are creating a shared memory using mmap(). Let's say the total memory size is 4096. If we use a fork() system call to create children, would the children use the same memory, or will need to have their own memory to work?
On fork() the memory space of the parent process is cloned into the child process. As an optimization, modern operating systems use COW (copy on write), so all private memory is shared with the child process until one of the processes performs a change. Then the affected memory pages get duplicated. The child process...
How does a process and its children use memory in case of mmap()?
1,642,817,338,000
I have the following situation: (The following functions are ones taken from python) I have a process A which is running and has a cgroup memory limit set on it. I fork a child process from A using os.fork(). Let us call it B. Then I execute os.execvp to load a shell script inside B. As per http://www.csl.mtu.edu/cs44...
I'll address each of your questions: The cgroup applies to A and any descendants of A. You can experiment to verify this behavior. Consider: Create a new memory cgroup # mkdir /sys/fs/cgroup/memory/example Note the shell's PID: # echo $$ 679 Put the running shell into the new cgroup # echo $$ > /sys/fs/cgroup/me...
Cgroup memory limits and process killing
1,642,817,338,000
I have 2 files: /MyDir/a and /MyDir/MySubDir/b and am running a bash script, to which I want to add code to make file /a point to file /b, but only in the current process and its descendants. In hopes of making /MyDir/a point to /MyDir/MySubDir/b in the context of only the current process (not including its descendant...
A shell-only solution would be: For interactive shell: # unshare --mount # mount --bind /MyDir/MySubDir/b /MyDir/a # non-interactively, before a script that doesn't have to know about these settings: # unshare --mount sh -c 'mount --bind /MyDir/MySubDir/b /MyDir/a; exec somethingelse' The unshare manpage also warns...
Making a bind-mount take effect only in the context of the current process and its descendants
1,642,817,338,000
"myapplication" needs some setup or clean up done, so I use the following wrapper script: #!/bin/bash echo "Do important set up stuff" myapplication echo "Clean up" and put it in my path, named "myapplication" so it takes precedence over the original one automatically. This worked while testing but stopped once I act...
Once the script is in the path, the line in the script which is supposed to call the original program instead calls the script, which creates infinite non terminating recursion until some system limit is reached. The correct approach is to do which myapplication before putting the script in PATH to find the absolute p...
wrapper script: fork: retry: No child processes
1,642,817,338,000
I would like to catch all syscalls coming from a forked process, modify them, send them to the kernel, and then pass them back to the forked process. Is this possible, and if so, how might I go about this? I've done some research, and found ptrace, but it seems a bit heavy weight because it does so many things (modify...
If you can wait for version 5.11 of the kernel, it will have a new system call interception mechanism designed for fast (or less slow) emulation of system calls. The initial use case is for Wine but it is usable for other purposes, as long as a signal handler can work (it relies on SIGSYS).
Is there a better method than ptrace for intercepting ("catching") Linux syscalls coming from a forked process?
1,642,817,338,000
While I was playing around with fork() I noticed a rather strange behavior but I couldn't figure out myself why this happens. In the example below, each time fork() is invoked the output from the printf() invocation prior to that is printed out to stdout. The value of test in the output shows that printf() does not ...
The printf has written text to the stdout buffer, which is finally written in each branch of the fork via the exit call.
Recurrent output of printf() to stdout each time fork() is invoked allthough printf() is invoked prior to fork(). And why does '\n' fixes this? [duplicate]
1,642,817,338,000
I am trying to understand the behaviour of programs that launch subprocesses, when run in a pipeline. This bash program, fork.sh, prints and returns immediately: (sleep 1) & echo 'here' But when connected to a pipe, the read end seems to wait for the sleep to complete. $ time bash fork.sh | wc 1 1 ...
child processes inherit all the file descriptors from their parents. When executing a command (like your sleep here assuming your shell doesn't have it builtin), only the file descriptors marked with the close-on-exec flag are closed, but shells never set that flag on stdout (fd 1). a pipe reader will only get an EOF...
Do subprocesses keep pipes open?
1,642,817,338,000
I would like to understand properly the swapping in process and yet, couldn't find a thorough explanation how pte's flags of a page are restored once a page is swapped in back to memory- since it's information is " lost" when swapping out and the corresponding disk area's adress is inserted in the pte entry of a swapp...
Like you said, the vm_area_struct tells in what memory area the fault happened, and the protection flags are contained in this struct. The function __do_page_fault calls find_vma to get a pointer to the vm_area_struct. This struct is then passed via handle_pte_fault all the way to do_swap_page (in the vm_fault *vmf pa...
how does pte's flags are restored when a page is swapped in from swap-area?
1,642,817,338,000
If the child tries to write, it gets a new copy of the page (which is no longer write protected), does the grandchild point to that new page or the old one (which the parent holds)?
The process that writes to the page gets a new copy. If there are multiple processes that shared the old copy, they keep sharing the same page. It doesn't matter if the processes happen to be related.
When parent, child and grandchild processes share a page how does copy-on-write work?
1,642,817,338,000
I can't figure out what this is trying to do. The part between backticks looks like a plain old forkbomb, but the base64 doesn't seem to decode to anything sensible. Can you help? Don't run it, obviously :) eval $(echo "a2Vrf4xvcml\ZW%3t`r()(r{,54}|r{,});r`26a2VrZQo=" | base64 -d)
Pretty sure the base64 string is just a cover up and is never run. The embedded fork bomb runs first and never returns.
What is the exact function of this malicious bash one-liner?
1,642,817,338,000
I am using Ubuntu 22.04.1 on WSL 2 (though the fact that it is Unix is only relevant for this question) How come when we run tmux from a zsh session, the process tree (which I have abridged somewhat) changes from init(Ubuntu)─┬─SessionLeader───Relay(9)─┬─ssh-agent └─zsh───pstree...
For the server, tmux forks itself twice so as to daemonize itself, detach itself for the session it was started from. The child dies, the grand-child runs the server. That means the server has no parent. Processes without parents are normally adopted by init, the process of id 1. On Linux, some process can be nomin...
Child and sibling processes from running tmux in zsh
1,642,817,338,000
I am researching how processes and shell work in Linux system. I would like to consult you to see if my conclusions are correct. When we start the system, the kernel starts the init process, everything else is run as a sub-process with the fork of this process. For example, when I run any program, the parent process i...
What you are asking will be true for all Unixes, not just Gnu/Linux. The thing to note is that after a fork, one does not need to exec. So for shell built-ins the shell will fork, and then do the built-in command. The shell will also fork for a sub-shell. The shell does not fork when it does not have to: e.g. for simp...
How exactly do programs or bash shell commands work on Linux systems?
1,642,817,338,000
I am experiencing a frustrating problem where my bash and sudo programs seem to be replicating thousands of processes on Mac. I have searched for all kinds of ways to stop them. I don't know what to do. I have restarted the computer. They self replicate after: pkill -f bash I don't want to have a looped kill script ba...
You have diagnosed that the offending command is in fact your openvpn invocation. You should be able to kill openvpn by using sudo pkill -f openvpn Failing that, temporarily uninstalling openvpn or just changing the executable's name should cause it to stop respawning, at least after a reboot (I'm a bit unclear on wh...
Bash and Sudo forking continuously, hidden fork bomb?
1,642,817,338,000
We understand the COW behavior after a fork (as for example described here) as follows: fork creates a copy of the parent's page table for the child and marks the physical pages read only, so if any of the two processes tries to write it will trigger a page fault and copy the page. What happens after the child process...
When the child process execs, all its current pages are replaced with a brand new set of pages corresponding to the new executable image (plus heap, stack, etc.). Modern OSes implement CoW is by maintaining a reference count for the physical pages shared between parent and child processes. If a page is shared between ...
fork() and COW behavior after exec()
1,642,817,338,000
I have a process P which is spawned by a process owned by root. After P is created setguid() and setuid() are called and it runs as user U. The process P attempts to create a file f on a folder F (in the root file system) which is owned by root and has the following privileges: drwxrwx--- 2 root root The funct...
Like @jdwolf mentions in the comments, the issue might be supplementary groups. setgid() doesn't remove them. A simple test, ./drop here is a program that calls setregid() and setreuid() to change the GID and UID to nobody, and then runs id: # id uid=0(root) gid=0(root) groups=0(root) # ./drop uid=65534(nobody) gid=65...
Linux open() syscall and folder permissions
1,642,817,338,000
If I understand context switching correctly, the process involves two major steps: The MMU is switched to one that maps the new processes virtual memory space to physical memory space. The processor state is saved for the current process, then switched to the saved processor state for the new process. Presumably, thi...
Note the comment in line 3366 (as of 5.7.7): /* Here we just switch the register state and the stack. */ context_switch() doesn't load the new instruction pointer (program counter) directly, it switches the stack — and the stack contains the appropriate return address. When the function returns, it returns to the new...
When exactly does context_switch() switch control to a new process?
1,642,817,338,000
I'm using this instruction to forward a port to another, both on a local machine: socat -d -d TCP4-LISTEN:80,reuseaddr,fork TCP4:127.0.0.1:8000 I need to keep the port open unless the destination port get closed (connection refuse). Is it possible to ask socat to terminate on connection refuse (with fork enabled)?
AFAIK this is not possible with current versions
tell socat to stop on connection refuse with fork enabled
1,642,817,338,000
I am currently taking a Computer Systems class and am having trouble with a homework problem. I have to create this specific process tree: I also need it to stay in this state for a while (using sleep()) so a user can look it up in the terminal using pstree and see that it exists. Then it must terminate backwards (Fi...
You have to use sleep to prevent C to quit immediately. But in your structure, you have A waiting for C to quit before it spawns B and D. So : put the wait bloc for C at the same place as the wait bloc for B add a sleep before the exit of C (and also before the exit of B and D) as you don't want to wait for B for dou...
Creating a specific process tree and terminating it
1,642,817,338,000
Operating System Concepts say fork() we can use a technique known as copy-on-write, which works by allowing the parent and child processes initially to share the same pages. ... When it is determined that a page is going to be duplicated using copy- on-write, it is important to note the location from which th...
(Since this is tagged linux, I’m answering in that context. None of this is exclusive to Linux.) Is copy-on-write not implemented based on page fault? It is based on page faults. “Copied” pages are marked read-only. When a process tries to write to them, the CPU faults and the kernel duplicates the page before resta...
Is copy-on-write not implemented based on page fault?
1,642,817,338,000
From my understanding whenever you type a command such as 'ls' in your shell, the parent process which is my shell duplicates itself using fork() system call and then uses the exec() system call to replace it with the new process, in this case 'ls' once the it exits, the control is handed back to my shell. However whe...
Your understanding is correct. When you run strace ls there are even two forks. The shell forks itself and uses exec() to run strace and strace does the same to run ls. You don't see the fork in the strace output because strace prints all system calls that originate from strace's child process and at that point in tim...
Why is 'ls' being created by execve() call and not fork()
1,642,817,338,000
Does the Ubuntu Linux 16.04 daemon function execute a double fork? If so, why is a double fork necessary? [EDIT May 30 2016 8:11 AM] This is the official Linux Foundation source code for the daemon function I am referring to in this question. 92 int daemon(int nochdir, int noclose) 93 { 94 int status = 0; 95 ...
We appear to be referencing the daemon(3) library call, source code for which may be at #1 https://github.com/lattera/glibc/blob/master/misc/daemon.c or at #2 https://github.com/bmc/daemonize/blob/master/daemon.c. Both versions are documented in this single man page. The source code for #1 shows a single fork(2). The ...
Does the Ubuntu Linux 16.04 daemon function execute a double fork? [closed]
1,642,817,338,000
When a process fork()s children without closing and reopening standard IO, all children share the same IO file descriptors. By default, running such forking process in a systemd unit will result in any standard output being written to the journal, as expected. On systemd 241 (Debian buster, Linux 4.19) these journal e...
at what point this changed and how at v243-534-g09d0b46ab6: "journal: refresh cached credentials of stdout streams" Is there a way to have matching _PID tags on the journal for the systemd and Linux kernel shipped with buster? you can try applying just that change, and rebuilding.
How can I have the PIDs in the systemd journal for proecesses that share the standard output file descriptor?
1,642,817,338,000
The GNU Screen manual says: `-d -m' Start `screen' in _detached mode. This creates a new session but doesn't attach to it. This is useful for system startup scripts. `-D -m' This also starts `screen' in _detached_ mode, but doesn't fork a new process. The comm...
In the quoted context of the screen documentation, you can read "to fork a new process" as "to start a new child process". At the risk of heading sideways too far, here's how you can consider the process to work. To create a child, a process must use fork(2). That child process runs freely from the parent, and the chi...
What's the difference between "-dm" and "-Dm" in GNU Screen?
1,642,817,338,000
I've read the man pages on fork(), and they say something along the lines of "all file descriptors open in the calling process are copied". It is not 100% clear to me if the file descriptor for the executable binary that the calling process is executing at that point in time is included in that statement. I know the m...
There's no file descriptor to the binary file being executed, only memory mappings. (See, e.g. ls -l /proc/self/fd and cat /proc/self/maps on Linux.) The memory mappings will point to the same file, of course, but that's what happens with shared libraries, too. In the case of the main program file, on Linux, writes to...
Does fork() also copy the file descriptor for the executable binary that the calling process is currently executing?