如何在两个不同的C程序之间实现同步?



首先,我不知道我是否可以很好地解释我的问题,或者你可以用适当的方式解决它。但我会尽量为你说清楚。

事实上,我有两个不同的C程序。 第一个是在控制台上简单循环打印一条消息:

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
int main ()
{
while(1)
{
printf("WAITINGn");
sleep(1);
}
}

第二个是阻塞程序,它等待事件(按下按钮(打开我的嵌入式板中的 led。

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <sys/select.h>
#include <sys/time.h>
#include <errno.h>
#include <linux/input.h>
#define BTN_FILE_PATH "/dev/input/event0"
#define LED_PATH "/sys/class/leds"
#define green "green"
void change_led_state(char *led_path, int led_value)
{
char    lpath[64];
FILE    *led_fd;
strncpy(lpath, led_path, sizeof(lpath) - 1);
lpath[sizeof(lpath) - 1] = '';
led_fd = fopen(lpath, "w");
if (led_fd == NULL) {
fprintf(stderr, "simplekey: unable to access ledn");
return;
}
fprintf(led_fd, "%dn", led_value);
fclose(led_fd);
}
void reset_leds(void)
{
change_led_state(LED_PATH "/" green "/brightness", 0);
}
int configure_leds(void)
{
FILE    *l_fd;
FILE    *r_fd;
char    *none_str = "none";
/* Configure leds for hand control */
r_fd = fopen(LED_PATH "/" green "/trigger", "w");


fprintf(r_fd, "%sn", none_str);

fclose(r_fd);

/* Switch off leds */
reset_leds();
return 0;
}
void eval_keycode(int code)
{
static int green_state = 0;
switch (code) {
case 260:
printf("BTN left pressedn");
/* figure out red state */
green_state = green_state ? 0 : 1;
change_led_state(LED_PATH "/" green "/brightness", green_state);
break;
}
}

int main(void)
{
int file;
/* how many bytes were read */
size_t  rb;
int ret;
int yalv;
/* the events (up to 64 at once) */
struct input_event  ev[64];
char    *str = BTN_FILE_PATH;
printf("Starting simplekey appn");
ret = configure_leds();
if (ret < 0)
exit(1);
printf("File Path: %sn", str);
if((file = open(str, O_RDONLY)) < 0) {
perror("simplekey: File can not open");
exit(1);
}
for (;;) {
/* Blocking read */
rb= read(file, &ev, sizeof(ev));
if (rb < (int) sizeof(struct input_event)) {
perror("simplekey: short read");
exit(1);
}
for (yalv = 0;
yalv < (int) (rb / sizeof(struct input_event));
yalv++) {
if (ev[yalv].type == EV_KEY) {
printf("%ld.%06ld ",
ev[yalv].time.tv_sec,
ev[yalv].time.tv_usec);
printf("type %d code %d value %dn",
ev[yalv].type,
ev[yalv].code, ev[yalv].value);
/* Change state on button pressed */
if (ev[yalv].value == 0)
eval_keycode(ev[yalv].code);
}
}
}
close(file);
reset_leds();
exit(0);
}

当我执行第二个代码时,程序开始等待事件打开/关闭 led。

我的问题是:

如何在两个程序之间进行交互?我想执行第一个 --> 它开始为我打印"等待",直到我按下按钮 -> LED 打开 ->然后它返回到第一个程序并重新开始打印"等待"在控制台上。

我不知道我是否很好地解释了这个问题,但我希望你能帮助我!谢谢。

你需要两个程序之间的通信机制。这也称为进程间通信。

通常,您有几个选项来实现此目的(取决于您使用的操作系统,并非所有选项都可用(:

共享
  • 内存/共享文件
  • 消息传递(例如通过套接字(
  • 管道
  • 信号

可以在此处找到有用的介绍。

最新更新