static char *TCPCommand; static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int SetUpTCPtoSendInformation(char option[], char *command) { pthread_mutex_lock(&mutex); // 加锁 if (strstr(option, "set")) { TCPCommand = malloc(strlen(command) + 1); if (TCPCommand == NULL) { CON_LOG("Failed to set and obtain TCP command variable memory allocation"); goto fail; } strcpy(TCPCommand, command); goto succeed; } else if (strstr(option, "get") && TCPCommand != NULL && strlen(TCPCommand)) { strcpy(command, TCPCommand); memset(TCPCommand, '\0', strlen(TCPCommand)); free(TCPCommand); goto succeed; } memset(command, 0, sizeof(command)); strcpy(command, ""); fail: pthread_mutex_unlock(&mutex); // 解锁 return 0; succeed: pthread_mutex_unlock(&mutex); // 解锁 return 1; } 修改程序为第一次调用option参数为set,第二次调用option只能为get ,如果第二次参数为set,那就等待到后面的调用参数为get后,在把option参数为set的值放进TCPCommand
时间: 2024-04-08 15:34:08 浏览: 79
根据您的要求,修改后的程序如下所示:
```c
static char *TCPCommand;
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int SetUpTCPtoSendInformation(char option[], char *command) {
static int isFirstCall = 1;
pthread_mutex_lock(&mutex); // 加锁
if (isFirstCall && strstr(option, "set")) {
TCPCommand = malloc(strlen(command) + 1);
if (TCPCommand == NULL) {
CON_LOG("Failed to set and obtain TCP command variable memory allocation");
goto fail;
}
strcpy(TCPCommand, command);
isFirstCall = 0;
goto succeed;
} else if (!isFirstCall && strstr(option, "get") && TCPCommand != NULL && strlen(TCPCommand)) {
strcpy(command, TCPCommand);
memset(TCPCommand, '\0', strlen(TCPCommand));
free(TCPCommand);
isFirstCall = 1;
goto succeed;
}
memset(command, 0, sizeof(command));
strcpy(command, "");
fail:
pthread_mutex_unlock(&mutex); // 解锁
return 0;
succeed:
pthread_mutex_unlock(&mutex); // 解锁
return 1;
}
```
这样修改后,第一次调用时将`isFirstCall`设置为0,第二次调用只有当`isFirstCall`为0且`option`为"get"时才会执行设置命令的操作。如果第二次调用的`option`为"set",则会等待到后续的调用中`option`为"get"时,再将第一次调用的值放入`TCPCommand`中。
阅读全文