So I am building my own shell, and one of the features is to list all background running jobs, their name, PID, job number similar to bash with it's status i.e is it suspended or running. I have to also print the exit status code of background jobs which just ended. Now I was wondering if there is a system call that will do this for me, or a C api call, once they are running in the back ground, or do I have to write my own job function that will do what I just mention? Thanks. I am doing this in C using Linux.
-
Not using system at all. System is like a shell already, I need to implement the 'ps' is there a way to get all the child pids, etc which is needed? – NoNameY0 Mar 09 '13 at 18:52
-
You mean all the processes on the system or just the ones started in the shell? – teppic Mar 09 '13 at 18:54
-
@teppic the ones started in the shell. If you put 5 commands in the background using & when you type jobs, I want to list all 5. – NoNameY0 Mar 09 '13 at 18:59
-
@RichardMckenna: I guess you'd have to get the shell's pid and the same technique as the pstree util. – teppic Mar 09 '13 at 19:01
-
Well, since `ps` is presumably written in C, there is certainly a way to do what you're trying... – Carl Norum Mar 09 '13 at 19:03
2 Answers
A quick and easy way is to search /proc
, as every running process has a directory in here that is equal to its PID, together with the name and state details. You can use regular stdio functions for that.
You might want to browse the psmisc source code, as this contains a set of standard Linux utilities designed to interface with /proc
.

- 8,039
- 2
- 24
- 37
For your concrete task (shell-like jobs control), you need to write such functions by self. By the way, the most of info you already have and should to keep around anyway.
Child's PID should be kept for waitpid(2).
Command line used for start the child process should be kept because process may change his argv[0], therefore, the original line will be lost.
Job number is purely internal thing for the shell and the OS does not, cannot and will not care about it (i.e. if you won't care about job number, then no one will care about it for you). As you see, only you (i.e. your process) has the needed info.
Another reason is portability. Even if assume, that information from procfs (/proc) on Linux is enough for you, on FreeBSD all these things are quite different matters -- you will need to work through kvm(3) interface. On Mac OS X you will need third way -- there no procfs and kvm(3) is obsolete some time ago.
Conclusion: you may dance around system differences but it will give you only part of information. From another hand, you anyway have or should to have that information floating around in your process. Just use it, it will be far simpler and far more portable.

- 121
- 3