Assuming that you write the content of this macro to a file then call system()
on that file, you have to use chmod(filename, 0755);
before system()
to make it executable.
(http://man7.org/linux/man-pages/man2/chmod.2.html)
Ouch, I just saw the edit in the question!
There is no chance that system(AINinit);
could work as is.
system()
requires a command line similar to what you would type in the terminal (not the content of a script file).
You need to use a file, as in the first part of this answer.
#define AINinit "\
#!/bin/bash \n\
path=`/sys/devices/bone_capemgr.*/slots` \n\
echo <password> | sudo -S echo cape-bone-iio > $path \n\
"
// convenient error checking omitted everywhere...
FILE *f=fopen("my_script", "w");
fputs(AINinit, f);
fclose(f);
chmod("my_script", 0755);
system("./my_script");
Alternatively you could change the macro so that you don't use a script file.
#define AINinit "\
echo <password> | sudo -S echo cape-bone-iio > `/sys/devices/bone_capemgr.*/slots`"
system(AINinit);
Note that, as mentioned in the comments, echoing the password is a dangerous solution (and which does not work well, for ssh
it does not for example).
I think that the permission problem message does not come from the attempt to execute some code with system()
.
I guess it is due to a bad usage of redirections with sudo
.
sudo a_command > a_file
performs the direction to a_file
before executing a_command
with some privileges.
A very common workaround is a_command | sudo tee a_file
in which a_command
is executed without privileges but tee
opens a_file
with privileges.
The inconvenient is that standard output of a_command
is also echoed on the terminal.
The command a_command | sudo dd of=a_file 2>/dev/null
should do the trick if the echoing is a problem.
All of this has nothing in common with the original question.