Zvi
Zvi

Reputation: 322

C program that executes command with argument from argv and print command output and pids

I'm new to C, and trying to figure out how I achieve the following:

./mycprog uname -r
5.3.0-42-generic
1234,5678

Where 1234 is the pid of mycprog and 5678 is the pid of uname

Thanks, Zvi

Upvotes: 0

Views: 90

Answers (1)

anastaciu
anastaciu

Reputation: 23832

argv is an array of strings each one contains a command line argument, including the name of the program, in your case:

argv[0]  ./mycprog 
argv[1]  uname 
argv[2]  -r

argc counts the number of arguments, in your case, 3.

You can use them as you wish. In case you have trouble you can find extensive documentation on the site on how to use these, e.g. Regarding 'main(int argc, char *argv[])'

To achieve what you need I would point you to:

getpid() to get the program's pid.

getuid() to get the user id.

getopt() is also a nice option to parse command line arguments.

Upvotes: 1

Related Questions