#include <stdio.h> #include <stdlib.h> #include <string.h> #include <pthread.h> static char *TCPCommand = NULL; static pthread_mutex_t mutex = P_MUTEX_INITIALIZER; int SetTCPCommand(char *command) { pthread_mutex_lock(&mutex); // 加锁 if (TCPCommand != NULL) { free(TCPCommand); } TCPCommand = malloc(strlen(command) + 1); if (TCPCommand == NULL) { printf("Failed to allocate memory for TCP command\n"); pthread_mutex_unlock(&mutex); // 解锁 return 0; } strcpy(TCPCommand, command); printf("set: %s\n", TCPCommand); pthread_mutex_unlock(&mutex); // 解锁 return 1; } int GetTCPCommand(char **command) { pthread_mutex_lock(&mutex); // 加锁 if (TCPCommand == NULL || strlen(TCPCommand) == 0) { printf("TCP command is empty\n"); pthread_mutex_unlock(&mutex); // 解锁 return 0; } *command = malloc(strlen(TCPCommand) + 1); if (*command == NULL) { printf("Failed to allocate memory for command\n"); pthread_mutex_unlock(&mutex); // 解锁 return 0; } strcpy(*command, TCPCommand); printf("get: %s\n", *command); free(TCPCommand); TCPCommand = NULL; pthread_mutex_unlock(&mutex); // 解锁 return 1; }怎么调用
时间: 2024-04-15 13:28:10 浏览: 112
你可以按照以下方式来调用`SetTCPCommand`和`GetTCPCommand`函数:
```c
#include <stdio.h>
#include <stdlib.h>
int main() {
char *command1 = "command1";
char *command2;
// 设置TCPCommand
int setResult = SetTCPCommand(command1);
if (setResult) {
printf("Successfully set TCPCommand\n");
} else {
printf("Failed to set TCPCommand\n");
return 1;
}
// 获取TCPCommand
int getResult = GetTCPCommand(&command2);
if (getResult) {
printf("Successfully got TCPCommand: %s\n", command2);
free(command2); // 使用完后记得释放内存
} else {
printf("Failed to get TCPCommand\n");
return 1;
}
return 0;
}
```
在上面的示例代码中,我们首先调用`SetTCPCommand`函数来设置TCPCommand的值为"command1"。然后,我们调用`GetTCPCommand`函数来获取TCPCommand的值,并将结果存储在变量`command2`中。
请注意,在使用完获取到的TCPCommand后,记得调用`free`函数释放内存。
希望这次能解决你的问题!如果你还有其他问题,请随时提问。
阅读全文