]> pd.if.org Git - pdclib/blob - platform/posix/functions/stdlib/system.c
PDCLib includes with quotes, not <>.
[pdclib] / platform / posix / functions / stdlib / system.c
1 /* system( const char * )
2
3    This file is part of the Public Domain C Library (PDCLib).
4    Permission is granted to use, modify, and / or redistribute at will.
5 */
6
7 #include <stdlib.h>
8
9 /* This is an example implementation of system() fit for use with POSIX kernels.
10 */
11
12 extern int fork( void );
13 extern int execve( const char * filename, char * const argv[], char * const envp[] );
14 extern int wait( int * status );
15
16 int system( const char * string )
17 {
18     char const * const argv[] = { "sh", "-c", (char const * const)string, NULL };
19     if ( string != NULL )
20     {
21         int pid = fork();
22         if ( pid == 0 )
23         {
24             execve( "/bin/sh", (char * * const)argv, NULL );
25         }
26         else if ( pid > 0 )
27         {
28             while( wait( NULL ) != pid );
29         }
30     }
31     return -1;
32 }
33
34 #ifdef TEST
35 #include "_PDCLIB_test.h"
36
37 #define SHELLCOMMAND "echo 'SUCCESS testing system()'"
38
39 int main( void )
40 {
41     FILE * fh;
42     char buffer[25];
43     buffer[24] = 'x';
44     TESTCASE( ( fh = freopen( testfile, "wb+", stdout ) ) != NULL );
45     TESTCASE( system( SHELLCOMMAND ) );
46     rewind( fh );
47     TESTCASE( fread( buffer, 1, 24, fh ) == 24 );
48     TESTCASE( memcmp( buffer, "SUCCESS testing system()", 24 ) == 0 );
49     TESTCASE( buffer[24] == 'x' );
50     TESTCASE( fclose( fh ) == 0 );
51     TESTCASE( remove( testfile ) == 0 );
52     return TEST_RESULTS;
53 }
54
55 #endif