2016-02-16 35 views
-4

有關msg1.cpp如何進入第二個循環的任何建議?我編譯並執行這兩個程序並且不會收到錯誤消息。當我編譯並執行msg2.cpp時,它會提示用戶輸入一些文本。當用戶輸入文本時msg1.cpp顯示用戶輸入。問題是msg1.cpp不會提示用戶'輸入一些文本',因爲它沒有進入循環。 64行是程序進入循環的時候。程序應該工作,因爲運行不再等於零,它等於一! 不會發布msg2.cpp源代碼,因爲msg2.cpp與我的問題無關。程序未進入第二循環?

//msg1.cpp 
/* Here's the receiver program. */ 

#include <stdlib.h> 
#include <stdio.h> 
#include <string.h> 
#include <errno.h> 
#include <unistd.h> 

#include <sys/types.h> 
#include <sys/ipc.h> 
#include <sys/msg.h> 

#define MAX_TEXT 512 
using namespace std; 

struct my_msg_st { 
    long int my_msg_type; 
    char some_text[BUFSIZ]; 
    //char some_text[MAX_TEXT]; 
}; 

int main() 
{ 
    int running = 1; 
    int msgid; 
    struct my_msg_st some_data; 
    long int msg_to_receive = 0; 
    char buffer[BUFSIZ]; 
    char some_text[MAX_TEXT]; 
    //string input; 

/* First, we set up the message queue. */ 

    msgid = msgget((key_t)1234, 0666 | IPC_CREAT); 

    if (msgid == -1) { 
     fprintf(stderr, "msgget failed with error: %d\n", errno); 
     exit(EXIT_FAILURE); 
    } 
/* Then the messages are retrieved from the queue, until an end message is encountered. 
Lastly, the message queue is deleted. */ 

    while(running) { 
     if (msgrcv(msgid, (void *)&some_data, BUFSIZ, 
        msg_to_receive, 0) == -1) { 
      fprintf(stderr, "msgrcv failed with error: %d\n", errno); 
      exit(EXIT_FAILURE); 
     } 
     printf("You wrote: %s", some_data.some_text); 
     if (strncmp(some_data.some_text, "end", 3) == 0) { 
      running = 1; 
     } 
    } 

    // msgctl performs control operations on system V message queue with identifier msqid 
    /*if (msgctl(msgid, IPC_RMID, 0) == -1) { 
     fprintf(stderr, "msgctl(IPC_RMID) failed\n"); 
     exit(EXIT_FAILURE); 
    }*/ 

    // Need to reset value, before entering second loop 
    // At this point enters loop, prompts user enter text 
    while(running) { 
     printf("Enter some text: "); 
     for (int i = 1; i < running; i++){ 
     fgets(buffer, BUFSIZ, stdin); 
     some_data.my_msg_type = 1; 
     strcpy(some_data.some_text, buffer); 
     } 
     if (msgsnd(msgid, (void *)&some_data, MAX_TEXT, 0) == -1) { 
      fprintf(stderr, "msgsnd failed\n"); 
      exit(EXIT_FAILURE); 
     } 
     if (strncmp(buffer, "end", 3) == 0) { 
      running = 0; 
     } 
    } 

    exit(EXIT_SUCCESS); 
} 
+4

第一個循環在while(running)計算爲「true」時運行,但我從來沒有看到從循環中'running'設置爲'0'或'break'。 –

+0

C++有一個布爾類型。 'running'看起來像一個布爾變量,但是你已經將它聲明爲一個整數。爲什麼? – Steve

+0

不要緊,這一切看起來像在'.cpp'文件中的C代碼... – Steve

回答

1

這是因爲當some_data.some_text等於"exit",你設置running一個,不。您應該首先將其設置爲零以退出第一個循環。

將其設置爲零,然後(在第一個循環之後)將其設置爲1。

+0

我做了這個修正和程序仍然沒有進入第二個循環! – ep7network

+1

@ ep7network,你在第二次循環之前讓'running'等於1嗎? – ForceBru

+0

是的。我離開第一個循環後修改了運行= 1! – ep7network