我正在做一個實驗專案(只是為了好玩),我需要一種方法來控制我的行程分叉的“節奏”。基本上,我有一個程式可以自己分叉而不附加到它的孩子。子行程通過execl
.
// other includes
#include "hook.h"
int
main()
{
const char* progname = "main";
unsigned int child_i;
pid_t pid;
for (child_i = 0; child_i < 3; child_i )
{
// Does some irrelevant stuff here
hook_take();
pid = fork();
if (pid == 0)
{
execl(progname, progname, NULL);
}
else
{
hook_free();
}
}
return 0;
}
這里的想法是創建一個程序樹,如下所示:
main
|-p0
| |-p00
| | |-p001
| | |-p002
| | |-p003
| |-p01
| | |-p011
| | |-p012
| | |-p013
| |-p02
| | |-p021
| | |-p022
| | |-p023
|-p1
| |-p10
| | |-p101
| | |-p102
| | |-p103
| |-p11
...
然而,這最終會創建過多的行程并且系統變得不穩定。這就是為什么我選擇使用共享庫 ( hook.h
) 在達到最大行程數時阻止行程的原因。這是作業hook_take()
和hook_free()
。它們在單獨的hook.h
檔案中定義。
#ifndef HOOK_H
#define HOOK_H
#ifdef __cplusplus
extern "C"
{
#endif
#define MAX_HOOKS 1000
extern unsigned int _hooks_count;
void hook_take();
void hook_free();
#ifdef __cplusplus
}
#endif
#endif /* HOOK_H */
并在hook.c
.
#include "hook.h"
#include <unistd.h>
unsigned int _hooks_count = 0;
void
hook_take()
{
while (_hooks_count == MAX_HOOKS)
{
sleep(1);
}
_hooks_count ;
}
void
hook_free()
{
if (_hooks_count > 0)
{
_hooks_count--;
}
}
hook.c
被編譯為共享庫并動態鏈接到主程式。
經過一番研究,我很快意識到這行不通。因為每個行程都會創建自己的變數副本_hooks_count
。
解決這個問題的最簡單方法是什么,而不會遇到太多麻煩?請記住,這只是一個實驗專案,我的代碼不需要是企業級的或任何東西。
uj5u.com熱心網友回復:
有多種方法可以在 Linux 上實作行程間信號量。可以說 POSIX 信號量是最簡單的:
#define SNAME "/tmp/hook_count"
// PLEASE CHECK ALL ERROR CODES !!!
// In root process
sem_t *sem = sem_open(SNAME, O_CREAT, 0644, MAX_HOOKS);
// In child process after fork
sem_t *sem = sem_open(SEM_NAME, 0);
sem_wait(sem);
// In child process before exit
sem_post(sem);
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/400174.html