Linux create pid file

pidfile (3) — Linux Manuals

In bsd/libutil.h Ft struct pidfh * Fn pidfile_open const char *path mode_t mode pid_t *pidptr Ft int Fn pidfile_write struct pidfh *pfh Ft int Fn pidfile_close struct pidfh *pfh Ft int Fn pidfile_remove struct pidfh *pfh

DESCRIPTION

The pidfile family of functions allows daemons to handle PID files. It uses flopen(3) to lock a pidfile and detect already running daemons.

The Fn pidfile_open function opens (or creates) a file specified by the Fa path argument and locks it. If a file can not be locked, a PID of an already running daemon is returned in the Fa pidptr argument (if it is not NULL ) The function does not write process’ PID into the file here, so it can be used before Fn fork Ns ing and exit with a proper error message when needed. If the Fa path argument is NULL /var/run/ Ao progname Ac .pid file will be used.

The Fn pidfile_write function writes process’ PID into a previously opened file.

The Fn pidfile_close function closes a pidfile. It should be used after daemon Fn fork Ns s to start a child process.

The Fn pidfile_remove function closes and removes a pidfile.

RETURN VALUES

The Fn pidfile_open function returns a valid pointer to a Vt pidfh structure on success, or NULL if an error occurs. If an error occurs, errno will be set.

Rv -std pidfile_write pidfile_close pidfile_remove

EXAMPLES

The following example shows in which order these functions should be used. Note that it is safe to pass NULL to Fn pidfile_write , Fn pidfile_remove and Fn pidfile_close functions.

struct pidfh *pfh; pid_t otherpid, childpid; pfh = pidfile_open("/var/run/daemon.pid", 0600, &otherpid); if (pfh == NULL) < if (errno == EEXIST) < errx(EXIT_FAILURE, "Daemon already running, pid: %jd.", (intmax_t)otherpid); >/* If we cannot create pidfile from other reasons, only warn. */ warn("Cannot open or create pidfile"); > if (daemon(0, 0) == -1) < warn("Cannot daemonize"); pidfile_remove(pfh); exit(EXIT_FAILURE); >pidfile_write(pfh); for (;;) < /* Do work. */ childpid = fork(); switch (childpid) < case -1: syslog(LOG_ERR, "Cannot fork(): %s.", strerror(errno)); break; case 0: pidfile_close(pfh); /* Do child work. */ break; default: syslog(LOG_INFO, "Child %jd started.", (intmax_t)childpid); break; >> pidfile_remove(pfh); exit(EXIT_SUCCESS);

ERRORS

Bq Er EEXIST Some process already holds the lock on the given pidfile, meaning that a daemon is already running. Bq Er ENAMETOOLONG Specified pidfile’s name is too long. Bq Er EINVAL Some process already holds the lock on the given pidfile, but PID read from there is invalid. Bq Er EAGAIN Some process already holds the lock on the given pidfile, but the file is truncated. Most likely, the existing daemon is writing new PID into the file.

The Fn pidfile_open function may also fail and set errno for any errors specified for the fstat(2), open(2), and read(2) calls.

The Fn pidfile_write function will fail if:

Читайте также:  Собираем свой сервер linux

Bq Er EINVAL Improper function use. Probably called before Fn pidfile_open .

The Fn pidfile_write function may also fail and set errno for any errors specified for the fstat(2), ftruncate(2), and write(2) calls.

The Fn pidfile_close function may fail and set errno for any errors specified for the close(2) and fstat(2) calls.

The Fn pidfile_remove function will fail if:

Bq Er EINVAL Improper function use. Probably called not from the process which made Fn pidfile_write .

The Fn pidfile_remove function may also fail and set errno for any errors specified for the close(2), fstat(2), write(2), and unlink(2) system calls and the flopen(3) library function.

AUTHORS

An -nosplit The pidfile functionality is based on ideas from An John-Mark Gurney Aq jmg [at] FreeBSD.org .

The code and manual page was written by An Pawel Jakub Dawidek Aq pjd [at] FreeBSD.org .

SEE ALSO

  • pid_t (3) — overview of system data types
  • piecewisedefaultcurve (3) — piecewise-interpolated default-probability structure
  • piecewiseyieldcurve (3) — piecewise-interpolated term structure
  • piecewiseyoyinflationcurve (3) — Piecewise year-on-year inflation term structure.
  • piecewisezeroinflationcurve (3) — Piecewise zero-inflation term structure.
  • piecewisezerospreadedtermstructure (3) — Piecewise-zero-spreaded term structure.
  • pivot_scaled_sprite (3) — Rotates and stretches a sprite around a specified point. Allegro game programming library.

Источник

What is a .pid File in Linux?

On Linux, a “.pid” file is a process identification (PID) file. It is used to store the process ID (PID) of a running process. The PID is a unique number assigned to each process when it is created and is used to identify the process in the operating system. The .pid file is usually located in the /var/run or /var/run/ directory and is named after the process it represents. In this article, we will discuss what .pid files are, how they are used, and how to work with them.

What is a PID file?

A PID file is a simple text file that contains the PID of a running process. The file is created when the process starts and is deleted after the process ends. System administrators, system scripts and other processes use the PID file to identify and interact with the running process. These files are especially useful when it comes to service management, process monitoring, and signals.

For example, a service script can use the PID file to determine if a service is running or stop the service by sending a signal to the process. A system administrator can use the PID file to view information about the process or to terminate the process. This is done using commands such as “pgrep” and “kill”, which we will discuss in detail later in this article.

Creating a .pid file

Creating a .pid file is a simple process and can be done with a simple command. One way to create a “.pid” file in a script is to pipe the output of “$$” to a file (in Bash shell) −

$$ is a Linux variable that returns the PID of the calling process. In this case, it’s the PID of the shell.

Another way to create a .pid file is to use a simple script like the following −

#!/bin/bash # create file pid_file="process.pid" echo $$ > $pid_file count=0 while [ $count -le 10 ] do echo Going $count.. sleep 1 count=$(($count+1)) done

When this script is run it will spawn the process and create the .pid file containing the process ID.

Читайте также:  Windows после linux grub

Location of the .pid file

When it comes to the location of “.pid” files, there is no specific rule as to where they should be stored. However, there are some commonly used locations for these files. Typically, our process places files in /var/run. To avoid conflicts with other processes, we could go one step further and create a new directory, /var/run/myScript. However, some systems may have this directory owned by root, in which case it may not be possible to write the .pid file there. A second option would be the home (/home/user) directory.

Kill a process using a .pid file

One of the primary uses of “.pid” files is to kill a process while it’s running. If there is a .pid file, we can get the PID of the file and then use it with xargs and kill. This ensures that we only need to know the name and location of the “.pid” file and not the PID itself.

$ cat process.pid | xargs kill

This command will take the contents of the .pid file, which is the process ID, and pass it as an argument to the kill command. This ensures that we only stop the exact process we want, instead of having to manually search for the process.

Guarantee a single instance of an application

Another use for .pid files is to ensure that only a single instance of an application is running. To do this, we need to remove the .pid file at the end of our run and add a check at the beginning to see if a .pid file exists. This can be done using the following script −

#!/bin/bash pid_file="process.pid" if [ ! -f $pid_file ]; then echo $$ > $pid_file count=0 while [ $count -le 10 ] do echo Going $count.. sleep 1 count=$(($count+1)) done rm $pid_file else echo "Process already running" fi

In this script, we first check if the “.pid” file exists. If it doesn’t exist, we proceed to create the file and run the script. Once the script has finished running, the .pid file is deleted. However, if the .pid file already exists, the script is already running, so the message «The process is already running» is displayed and the script does not run.

This is a simple yet effective way to ensure that only one instance of the script is running at any given time.

Conclusion

In this article, we discuss what .pid files are and how they are used in Linux. We cover creating and locating “.pid” files, as well as tasks that can be performed with .pid files, such as killing a process and ensuring a single instance of an application. .pid files are a convenient way to track running processes and allow system administrators, scripts, and other processes to easily identify and interact with running processes. Understanding how to use .pid files can greatly simplify the process of administering and maintaining Linux systems.

Источник

Write a PID file in bash

To write a PID-file of a just created background process you can simply use the variable $! like this:

/usr/local/bin/program & echo $! > /var/run/program.pid

I need this to fork a little daemon written in PHP. Yes, I could use pcntl_fork(), but my goal was, saving the recompilation of PHP and any changes to the code. Normally, I used a little tricky syntax to fork the PHP-process:

((/usr/local/php -f /var/daemon/queue.php)&)

This is quite cool, because the process now runs in the background, and we can close the shell. But what happens, when the process dies? This is a problem and I tried to combine the first and the second snippet to get the PID in a file and look continually over the process. First I wrote the backgrounding to a little shellscript:

#!/bin/bash /usr/local/php -f /var/daemon/queue.php & echo $! > /var/run/queue.pid

And started the whole thing by ((queue.sh) &).

Читайте также:  Пароль от пользователя root линукс

But let’s try to combine both in a single statement. The result of my testing was an easy to read command, which spawns a programm as a daemon and additionaly writes it’s PID to a file:

((/usr/local/php/bin/php -f /root/queue.php) & echo $! > /var/run/queue.pid &)

For now, we have the process running and the according PID in a file. Let’s write a little watchdog, that will watch over the health of our daemon and creates a new process, when our daemon dies for some reason. I think the best solution for this job is a cron job. So let’s pack the stuff in a little shellscript.

You might also be interested in the following

Sorry, comments are closed for this article. Contact me if you want to leave a note.

© 2008 — 2023 Robert Eisele All rights reserved • Privacy Policy, Contact

Источник

Run program in UNIX and make pidfile for it

We sometime want to run a program and after than stop it.

For example, at boot time, we start an selenium. But after that, we want to stop it.

The question is, how we could stop it? One approach is using ps -ef | grep command. But it hard to match exactly program we want to stop. I think the correct way is using pidfile . pidfile is the file which store a process id (the process id of program we start)

This post will tell you 2 ways to create pid file

1. Using start-stop-daemon tool

Syntax of start-stop-daemon is

$> start-stop-daemon --start --chuid --background \ --make-pidfile --pidfile /var/run/.pid --exec $PROGRAM -- $PROGRAM-ARGUMENT

More details about program and its parameters

 `--chuid username`: set user you want to run program in. (It is best practice if we dont run it with root access) `--backgroud`: make program run in background `--make-pidfile`: force program to create pidfile (sometime it doesnot work. check document of `start-stop-daemon` for more details) `--pidfile`: specify pidfile for the program `$PROGRAM-ARGUMENT`: is ARGUMENT for the program
SELENIUM_PROGRAM=/usr/bin/java SELENIUM_OPTS="-jar /home/vagrant/selenium-server-standalone-2.24.1.jar" SELENIUM_PID_NAME=selenium start-stop-daemon --start --chuid vagrant --make-pidfile --background --pidfile \ /var/run/$SELENIUM_PID_NAME.pid --exec $SELENIUM_PROGRAM -- $SELENIUM_OPTS

2. Using bashscript

Bashscript also support a method $! to get process id of last command

So, if we want to start our selenium server and make pidfile, we can write a script like this

SELENIUM_PROGRAM=/usr/bin/java SELENIUM_OPTS="-jar /home/vagrant/selenium-server-standalone-2.24.1.jar" SELENIUM_PID_NAME=selenium SELENIUM_LOG_FILE=selenium.logfile su -c "$SELENIUM_PROGRAM $SELENIUM_OPTS 2>&1 >>$SELENIUM_LOG_FILE &" vagrant PID=$! echo $PID > $SELENIUM_PID_NAME.pid

3. Stop process right way

Now, if you want to stop a program which process id was store in pidfile , it quite easy

# using cat and xargs and kill $> cat | xargs kill # using start-stop-daemon tool again $> start-stop-daemon --stop --pid

Kien Nguyen Trung

A father, husband and Elixir lover.

Источник

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