• Ogłoszenie:

Xclock using c language

Dyskusje i problemy z Unix'ami

Xclock using c language

Postprzez NilophirHaltos 12 Kwi 2023, 13:53

reklama
i am working on a c program that takes a name of process that the user wants to kill like xclock for example , so the program will get xclock pid and do the kill command to kill xclock , any ideas how can i get the pid from pid name and kill it
NilophirHaltos
~user
 
Posty: 11
Dołączenie: 19 Sty 2023, 15:45



Xclock using c language

Postprzez NilophirHaltos 11 Paź 2023, 09:00

here are some ideas on how to get the PID from a process name and kill it in C:

To get the PID from a process name, you can use the getpgid() function. This function takes a process name as an argument and returns the PID of that process.

To kill a process, you can use the kill() function. This function omeglz online2yu takes the PID of the process to be killed as an argument.

Here is a simple C program that gets the PID of a process name and kills it:

C
#include <stdio.h>
#include <unistd.h>

int main(int argc, char *argv[]) {
if (argc != 2) {
printf("Usage: %s <process name>\n", argv[0]);
return 1;
}

pid_t pid = getpgid(argv[1]);
if (pid == -1) {
printf("Process %s not found\n", argv[1]);
return 1;
}

int ret = kill(pid, SIGKILL);
if (ret != 0) {
printf("Failed to kill process %s\n", argv[1]);
return 1;
}

return 0;
}
Use code with caution. Learn more
To compile and run this program, you can use the following commands:

gcc kill_process.c -o kill_process
./kill_process xclock
This will kill the xclock process, if it is running.
NilophirHaltos
~user
 
Posty: 11
Dołączenie: 19 Sty 2023, 15:45




Powróć do System Linux / Unix

Kto jest na forum

Użytkownicy przeglądający to forum: Brak zarejestrowanych użytkowników oraz 6 gości