Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

concatenating strings to use on the command line

My assignment wants me to gather all the processes being run by using a ps -ef | grep -v grep | grep <PID#> I need to use, but I am receiving an illegal hardware instruction. here is the code:

//some code^

int PID = getpid();
char command[] = "ps -ef | grep -v grep | grep ";
char PIDString[12];

sprintf(PIDString, "%i", PID);
system("clear");

//These print just fine
//printf("%s\n",command);
//printf("ID %s",PIDString);

strcat(command, PIDString);

system(command);

When I tried to insert a %i. into the string "grep …%.." it wouldn’t work. Is there a way to do this instead of changing the int to a string and concatenating them. Please let me know what I’m missing to grasp.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

char command[] = "ps -ef | grep -v grep | grep ";

Your compiler will allocate just enough memory to hold this string.

If you want to have additional space available, you could make sure by specifying the size of the array.

char command[100] = "ps -ef | grep -v grep | grep ";

You may wish to define a constant to hold that value, rather than just a magic number.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading