access bash from C program?

Ben Scott dragonhawk at gmail.com
Mon Jun 2 12:00:52 EDT 2008


On Mon, Jun 2, 2008 at 11:19 AM, Labitt, Bruce
<labittb1 at tycoelectronics.com> wrote:
> I've been scratching my brains here a bit.  Is there an easy way to get
> access to the shell (bash) from within a C program?

  The system(3) standard library function will let you pass a command
to the OS for it to run.  This is portable C, and should work on just
about any OS.  You have to format the command string as the OS would
normally accept it.  So, for example, if you would need to escape
characters from the shell, you need to do so in the system(3) string
as well.

  However...

> I'd like to run the equivalent of the command "$ ulimit -s hard"

  You won't be able to do that by invoking any OS command.  ulimit
settings are set for the current process.  Invoking the shell from
your C program will spawn a new process for that shell.  So you'll end
up setting the ulimit for that shell.  Since the shell will then
immediately exit back to your C program, that's not very useful.

  Further, on Unix-like systems, processes are protected from each
other.  So a child process (the shell, in this case) cannot modify its
parent process's environment (your C program).  So doing this by
invoking an OS command from your C program is not feasible.

  There are two approachess that might work here:

  #1: Wrap your C program in a shell script which set any needed
limits and then invokes the C program.  Child processes inherit their
environment from their parent, so the limit set in the wrapper script
will be inherited by your C program.  (The "ulimit" command is a Bash
built-in, so it's not actually starting another process when you
invoke it.)  This approach is a little kludgey, but it's something you
already know how to do.

  #2: Use the OS's native library and system functions to set limits
from within your C program.  This will mean a bit more work on your
part to learn about them, but means you don't have to mess around with
wrapper scripts, yielding a cleaner implementation.  I believe "man 2
ulimit" will get you started.  (IIRC, ulimit() is a system call, not a
library function.  I could be wrong.  If it says there is no such
command, try "man 3 ulimit".)

-- Ben


More information about the gnhlug-discuss mailing list