how do i get a list of all the processes running in the background

I am writing a C++ program on a POSIX compliant OS. I know many shells have "jobs" command that provide these services, but my program is in c++ and there is no specific "jobs" command that I could use. Any way around it?
Last edited on
One way is to use popen to call the ps command. Do a man on popen. Depending on your operating system here may be APIs that you can call directly.
I am using Wiindows
I guess next time you should post in the Windows Programming forum. You can run a system command (if Windows has one) and redirect the output to a file, then open the file and parse it.
Well, my computer is using Windows but I am writing the program in a Linux environment (using putty i was able to gain access to my school's linux server). It is a c++ program btw. Anyways, i looked into the ps command, and I don't think it could work in this situation.
Last edited on
Why not? The ps command lists running processes. You can even get a list of all processes besides your own. Can you explain why it wouldn't work for you?
my program reads command line input, and parses the input in order to interpret the first token. The user must input the keyword "jobs" in order to list all the processes that are running in the background (actually just the process ids). So I would need something like,

1
2
if(strcmp(argv[0], "jobs") == 0)
ps


but the ps is undefined as is indicated by the g++ upon compilation.
Of course, that is invalid syntax.
¿what about reading /proc?
Well, commands are not directly executed as the input is put into an array and upon "jobs" input i have to implement some system call that would list all the currently running processes. This is much harder than I thought.
Did you look at popen? This is exactly the way I do this all the time:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

char Buffer[ 1024 ];

/*    Get user input:    */


/*    Build command string:    */

    sprintf( Buffer, "ps " );

/*    Run popen():    */


FILE *ptr = popen( Command, "r" );

if( NULL != ptr )
    {
    while( fgets, Buffer, sizeof( Buffer ), ptr )
        {
        /*    Parse out the pids here:    */

        }    /*    while( ... )    */

    pclose( ptr );

    }    /*    if( NULL != ptr )     */



kooth, thanks a bunch for providing me with a detailed answer. I am starting to get hold of this stuff now. Moderator can now archive this thread.
You're welcome a bunch - I hope you can use it! Please mark this thread as resolved when you feel that it is. Good luck!
FILE *ptr = popen( Command, "r" );

Didn't really get the arguments of popen. what is r?
The man page says it is the file mode for the stream: r means read-only. I messed up my example: On line nine it should be:

1
2
    sprintf( Command, "ps " );


NOTE: Add the appropriate flags to the ps command to suit your needs.
Topic archived. No new replies allowed.