0

We are using C in Linux. Is there any possibility that system() function can behave in an unexpected manner, especially when we handle signals?

We found that sometimes, the system() function blocks the execution or it throws SIGSEGV.

e.g:

system ( "/bin/mv a b" );

Are there any known flaws in using system() that would explain this?

Tim Post
  • 33,371
  • 15
  • 110
  • 174
abubacker
  • 4,638
  • 6
  • 32
  • 35

2 Answers2

2

The system() function does what it is supposed to do perfectly well. The behaviour is pretty reliable as long as it is invoked correctly. It has two modes of operation:

  1. Check whether there is a command interpreter available - when the argument is a null pointer.
  2. Run the command given, waiting for the command to complete before returning.

So, the system() statement blocks until the shell that runs the command completes. On Unix-like systems, the command invoked is effectively:

"sh", "-c", "...argument to system...", NULL

This means that the string passed is interpreted by the shell. How long that takes depends on the command that is executed. You can consider using the shell notations to run the command in background if you need to:

system("( /bin/mv a b & )");

There are few circumstances where system() will itself generate SIGSEGV. You would have to pass it an invalid pointer, a pointer to somewhere invalid in the program.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
0

The system() call is supposed to block until execution is finished. If it takes an hour to move a to b, the process or thread calling system() will block for an hour. Knowing this, strange behavior can be explained.

If you expect system() to return immediately, it probably means that you expect code that runs after calling it to have been entered by the time you see the strange behavior. It is very likely that, due to system() taking longer than expected, some area of memory wasn't allocated or initialized. This is likely the cause of the segmentation fault when another thread or process tried to access it.

In other words, if you didn't expect system() to block, you probably assumed that code coming after it would run much sooner than it actually did.

Debunking that would be a topic for another question. The answer to this one is no, you aren't seeing flaws in the system() function, it is behaving exactly as expected.

Tim Post
  • 33,371
  • 15
  • 110
  • 174
  • http://stackoverflow.com/questions/3838565/replace-system-with-non-blocking-function – Michael Dillon Apr 12 '11 at 06:04
  • 1
    @Michael - I think the SEGV the OP is seeing is (likely) due to code coming after system() not being reached in the expected amount of time, since the OP didn't expect it to block. I updated my answer. Since the OP is passing a string literal as an argument, it seemed a likely explanation. – Tim Post Apr 12 '11 at 06:42