ubuntu kill background running process

本文介绍了一个简单的Shell脚本,该脚本用于查找并终止指定名称的进程。通过使用ps和grep命令组合,脚本能够将匹配的进程记录到日志文件中,并进一步筛选出需要终止的目标进程。
ps -ef | grep Insight3 > /tmp/killtxt.log
ps -ef | grep firefox >> /tmp/killtxt.log
cat /tmp/killtxt.log
cat /tmp/killtxt.log | while read lineStr
do
    idStr=`echo $lineStr | awk '{print $4}'`
    pidStr=`echo $lineStr | awk '{print $2}'`
    if [ "$idStr" == "0" ]; then
    echo "no need to kill $pidStr"
    else
    echo "kill $pidStr"
    kill $pidStr
    fi
done
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/wait.h> #include <signal.h> #define MAX_INPUT 1024 #define MAX_ARGS 64 // 全局变量记录后台进程PID pid_t background_pid = -1; void execute_command(char **args, int background) { pid_t pid = fork(); if (pid == 0) { // 子进程 execvp(args[0], args); perror("execvp failed"); exit(EXIT_FAILURE); } else if (pid > 0) { // 父进程 if (!background) { waitpid(pid, NULL, 0); // 等待前台进程结束 } else { background_pid = pid; // 记录后台进程PID printf("[%d] running in background\n", pid); } } else { perror("fork failed"); } } int main() { char input[MAX_INPUT]; char *args[MAX_ARGS]; char *token; int background; while (1) { printf("mysh> "); fflush(stdout); // 读取用户输入 if (!fgets(input, MAX_INPUT, stdin)) break; // 处理换行符 input[strcspn(input, "\n")] = '\0'; // 解析输入 int i = 0; token = strtok(input, " "); while (token != NULL && i < MAX_ARGS - 1) { args[i++] = token; token = strtok(NULL, " "); } args[i] = NULL; // 空命令处理 if (i == 0) continue; // 检查后台运行标识 (&) background = 0; if (i > 0 && strcmp(args[i-1], "&") == 0) { background = 1; args[i-1] = NULL; } // 内建命令处理 if (strcmp(args[0], "exit") == 0) { break; } else if (strcmp(args[0], "stop") == 0) { if (background_pid != -1) { kill(background_pid, SIGTERM); printf("Terminated process [%d]\n", background_pid); background_pid = -1; } else { printf("No background process running\n"); } } else if (strcmp(args[0], "cd") == 0) { // 内建cd命令 if (args[1] && chdir(args[1]) != 0) { perror("cd failed"); } } else { // 执行外部命令 execute_command(args, background); } } return EXIT_SUCCESS; } 分析这段代码的功能
08-07
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值