php exec c program in background error
I'm trying to execute a program in the background using php. The c program is this.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) {
printf("hello\n");
int i =0;
printf("hello world\n");
FILE *fp;
fp = fopen("/home/gianpaolo/workspace/test/outputfile", "w+");
while(i < 60000000) {
fprintf(fp, "hello world\n");
i++;
}
fclose(fp);
}
and the php that runs the program goes like this
<?php
$out = array();
exec('/home/gianpaolo/workspace/test/test 2开发者_如何学C>&1', $out);
print_r($out);
?>
I'm triggering this code using a webpage that has a reference to this code. As you can see I'm printing the variable $out to see what's happening and this is what i get
Array ( [0] => Segmentation fault )
If I run any command line it works great but if I run this it won't any ideas?
---UPDATE--- I checked as suggested if the fp was NULL which in fact it was. So, how can I grant permission so it can open to write or create to write files?
Check the return value of your fopen
call.
I guess that the user which runs the webserver hasn't got enough permissions to write (or even read) the file. If that's the case, fopen
will return a NULL
pointer.
This is almost certainly because of 2 things
- You don't check for failure to open file (i.e.
fp
is null) - Your web server user (usually www-data or similar) does not have the permissions to open that file
combine those two and you are trying to write to a file you (www-data in this case) don't have permissions to and thus using a NULL
pointer in the fwrite
call in the C program, dereferencing a NULL
pointer in the fwrite
call causes a segfault
In short, remember your web server does not run as the same user, with the same permissions as you.
Edit: You will want to use the chmod
shell command to grant read & write permissions on the directory to "other" (unless you don't want to let anyone write there, just www-data, in which case you'll need to use chown
as well. Strictly speaking this part of the question lives on http://serverfault.com or http://unix.stackexchange.com
Did you check whether fp was NULL when it returned from fopen? As stated here:
If the file has been succesfully opened the function will return a pointer to a FILE object that is used to identify the stream on all further operations involving it. Otherwise, a null pointer is returned.
精彩评论