Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issuing system commands in Linux from C, C++

Tags:

c++

c

linux

system

I know that in a DOS/Windows application, you can issue system commands from code using lines like:

system("pause");

or

system("myProgram.exe");

...from stdlib.h. Is there a similar Linux command, and if so which header file would I find it in?

Also, is this considered bad programming practice? I am considering trying to get a list of loaded kernal modules using the lsmod command. Is that a good idea or bad idea? I found some websites that seemed to view system calls (at least system("pause");) in a negative light.

like image 222
8bitcartridge Avatar asked Nov 27 '22 12:11

8bitcartridge


2 Answers

system is a bad idea for several reasons:

  • Your program is suspended until the command finishes.
  • It runs the command through a shell, which means you have to worry about making sure the string you pass is safe for the shell to evaluate.
  • If you try to run a backgrounded command with &, it ends up being a grandchild process and gets orphaned and taken in by the init process (pid 1), and you have no way of checking its status after that.
  • There's no way to read the command's output back into your program.

For the first and final issues, popen is one solution, but it doesn't address the other issues. You should really use fork and exec (or posix_spawn) yourself for running any external command/program.

like image 68
R.. GitHub STOP HELPING ICE Avatar answered Dec 06 '22 12:12

R.. GitHub STOP HELPING ICE


Not surprisingly, the command is still

system("whatever");

and the header is still stdlib.h. That header file's name means "standard library", which means it's on every standard platform that supports C.

And yes, calling system() is often a bad idea. There are usually more programmatic ways of doing things.

If you want to see how lsmod works, you can always look-up its source code and see what the major system calls are that it makes. Then use those calls yourself.

A quick Google search turns up this link, which indicates that lsmod is reading the contents of /proc/modules.

like image 32
chrisaycock Avatar answered Dec 06 '22 12:12

chrisaycock