一、進程基本概念
進程是指正在執行中的程序,並且具有獨立運行的能力,是操作系統分配資源和時間的基本單位。進程包括進程式控制制塊和執行代碼兩部分。
每個進程都有唯一的進程號(PID),並且可以通過shell命令ps來查看系統中運行的所有進程及其狀態。
二、進程間通信(IPC)
在Linux中,進程間通信(IPC)是非常重要的。常見的IPC方式有:管道、信號、共享內存、消息隊列等。
共享內存是較高效的進程間通信方式之一,可以允許多個進程在同一段物理內存中進行讀寫操作。下面是獲取共享內存並進行操作的示例代碼:
#include <stdio.h> #include <stdlib.h> #include <sys/ipc.h> #include <sys/shm.h> #include <unistd.h> #define SHMSZ 27 int main() { char c; int shmid; key_t key = 5678; char *shm, *s; if((shmid = shmget(key, SHMSZ, IPC_CREAT | 0666)) < 0) { perror("shmget"); exit(1); } if((shm = shmat(shmid, NULL, 0)) == (char *) -1) { perror("shmat"); exit(1); } s = shm; for(c = 'a'; c <= 'z'; c++){ *s++ = c; } *s = '\0'; while(*shm != '*') { sleep(1); } exit(0); }
三、進程調度
進程調度是指操作系統根據一定的演算法從就緒隊列中選擇下一個進程,對其進行CPU分配,從而實現多個進程並發執行的過程。
Linux內核採用了搶佔式調度和時間片輪轉調度演算法。常用的調度演算法有:先來先服務、最短作業優先、優先順序調度、時間片輪轉調度等。
下面是進行進程優先順序調度的示例代碼:
#include <linux/sched.h> #include <linux/kernel.h> #include <linux/module.h> static int __init my_init(void) { printk(KERN_INFO "Hello, world!\n"); struct task_struct * p; for_each_process(p) { //遍歷所有進程 printk(KERN_INFO "name: %s, state: %ld, pid: %d\n", p->comm, p->state, p->pid); } return 0; } static void __exit my_exit(void) { printk(KERN_INFO "Bye, world!\n"); } module_init(my_init); module_exit(my_exit); MODULE_LICENSE("GPL");
四、進程狀態轉換
在Linux中,進程狀態可以分為就緒態、運行態、掛起態等幾種狀態。進程狀態的轉換涉及到進程阻塞、掛起、喚醒等操作。
下面是進程狀態轉換的示例代碼:
#include <stdio.h> #include <signal.h> #include <stdlib.h> #include <unistd.h> int main() { int count; pid_t pid; if ((pid = fork()) == -1) { perror("fork"); exit(1); } if (pid == 0) { for (count = 0; count < 10; count++) { printf("Child: %d\n", count); sleep(1); } exit(0); } else { sleep(5); kill(pid, SIGSTOP); //掛起子進程 printf("Parent has stopped child!\n"); sleep(5); kill(pid, SIGCONT); //恢復子進程 printf("Parent has resumed child!\n"); for (count = 0; count < 10; count++) { printf("Parent: %d\n", count); sleep(1); } } exit(0); }
五、多線程
在Linux中,一個進程可以包含多個線程,每個線程都可以獨立地運行和執行任務。線程可以大大提高程序的並發性,提高程序的效率。
下面是創建線程的示例代碼:
#include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> void *thread_function(void *arg){ printf("Thread function is running. Argument was %s\n", (char *) arg); sleep(3); //睡眠3秒 printf("Thread function is done.\n"); return NULL; } int main() { int res; pthread_t a_thread; void *thread_result; res = pthread_create(&a_thread, NULL, thread_function, "Hello world!"); if (res != 0) { perror("Thread creation failed"); exit(EXIT_FAILURE); } printf("Waiting for thread to finish...\n"); res = pthread_join(a_thread, &thread_result); if (res != 0) { perror("Thread join failed"); exit(EXIT_FAILURE); } printf("Thread joined, it returned %s\n", (char *) thread_result); printf("Main function is done.\n"); exit(EXIT_SUCCESS); }
原創文章,作者:APXFP,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/370954.html