【发布时间】:2016-06-23 00:42:14
【问题描述】:
我是 Linux C 编程领域的新手,请耐心等待。使用互斥锁和信号量找到了几个关于进程间同步(相同进程但不同实例)的线程,但与我的情况不完全匹配。我尝试关注他们并尝试创建一些示例,但没有一个对我有用。
最后在这里发帖寻求帮助。
我正在努力创建一个将通过以太网远程登录会话执行的实用程序。正如下面 USAGE 注释中所述,第一次调用将传递命令行参数 -init 将启动一个将始终运行的线程。在 -init 之后的所有调用都将具有 -c: 使用不同的十六进制代码指定的参数。
问题是当一个实例仍在处理另一个调用时,会带有不同的 -c: hex 代码值。有时这会造成第二次调用返回的响应返回到第一次调用的问题。 (这是因为终端设备正在快速发送对第二个命令的响应,而第一个命令仍在进行中)
寻找一些伪代码或参考,以帮助我同步可以防止在收到第一个命令的响应之前发送第二个命令的代码部分。
希望我解释得当。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <semaphore.h>
#include <fcntl.h>
#include <signal.h>
#include <time.h>
#include <ctype.h>
static volatile sig_atomic_t isRunning = 1;
/* Signal handler */
void signal_handler(int signal) {
switch (signal) {
case SIGINT:
case SIGTERM:
case SIGQUIT:
/* Graceful shutdown */
isRunning = 0;
break;
default:
break;
}
}
void* random_generator(void* data) {
fd_set readfd;
struct timeval timeout;
char buff[20];
struct tm *sTm;
do {
time_t now = time(0);
sTm = gmtime(&now);
strftime(buff, sizeof(buff), "%Y-%m-%d %H:%M:%S", sTm);
printf("%s\n", buff);
timeout.tv_sec = 1;
timeout.tv_usec = 0;
int ret = select(0, NULL, NULL, NULL, &timeout);
printf("Select returned: %d\n", ret);
} while (isRunning);
printf("Exiting thread...");
pthread_exit((void*) 0);
}
int main(int argc, char** argv) {
/*
* USAGE:
* 1st command -> ./util -init
* 2nd command -> ./util -c:<hexcode>
* 3rd command -> ./util -c:<hexcode>
* .......
*/
pthread_t mythread;
signal(SIGTERM, signal_handler);
signal(SIGINT, signal_handler);
signal(SIGQUIT, signal_handler);
if (argc == 2)
return 0;
if (strcmp(argv[1], "-c:") == 0) {
// TODO: Only one process should be executing this part at any point of time
...lock();
int count = 0;
do{
printf("Processing...%d\n", count);
}while(count++ < 30);
...unlock();
return 0;
} else if (strcmp(argv[1], "-init") == 0) {
// always running thread
printf("Starting thread...\n");
int ret = pthread_create(&mythread, NULL, random_generator, (void*) NULL);
if (ret)
printf("Failed starting thread\n");
else
printf("Thread started\n");
pthread_join(mythread, NULL);
}
return 0;
}
【问题讨论】:
-
互斥锁就是答案。如果互斥锁是拥有的,那么你必须等到你可以拥有它。你能告诉我们你看过什么吗?
-
@JerryJeremiah, link 是我试图在我的场景中理解和实施的一篇文章。我正在寻找的其他选项是条件互斥锁。
标签: c multithreading mutex semaphore interprocess