簡體   English   中英

如何從另一個函數打印變量?

[英]How can i print a variable from another function?

我嘗試用libssh示例中建立的一部分代碼制作ssh遠程命令,並嘗試在int main();這樣的執行函數外部打印輸出int main();

printf("Server output: %s", nbytes);
int exec_uname(ssh_session session) {

  ssh_channel channel;
  int rc;
  channel = ssh_channel_new(session);
  if (channel == NULL) return SSH_ERROR;
  rc = ssh_channel_open_session(channel);
  if (rc != SSH_OK) {
    ssh_channel_free(channel);
    return rc;
  }
  //Once a session is open, you can start the remote command with ssh_channel_request_exec():

  rc = ssh_channel_request_exec(channel, "uname -a");
  if (rc != SSH_OK) {
    ssh_channel_close(channel);
    ssh_channel_free(channel);
    return rc;
  }
  //If the remote command displays data, you get them with ssh_channel_read(). This function returns the number of bytes read. If there is no more data to read on the channel, this function returns 0, and you can go to next step. If an error has been encountered, it returns a negative value:
  char buffer[256];
  int nbytes;
  nbytes = ssh_channel_read(channel, buffer, sizeof(buffer), 0);
  while (nbytes > 0) {
    if (fwrite(buffer, 1, nbytes, stdout) != nbytes) {
      ssh_channel_close(channel);
      ssh_channel_free(channel);
      return SSH_ERROR;
    }
    nbytes = ssh_channel_read(channel, buffer, sizeof(buffer), 0);
  }
  if (nbytes < 0) {
    ssh_channel_close(channel);
    ssh_channel_free(channel);
    return SSH_ERROR;
  }
  //Once you read the result of the remote command, you send an end-of-file to the channel, close it, and free the memory that it used:
  ssh_channel_send_eof(channel);
  ssh_channel_close(channel);
  ssh_channel_free(channel);
  return SSH_OK;
}

您不能在函數外部訪問局部變量。 您可以在更廣泛的范圍內聲明它,例如global,這是最后的手段,或者將其傳遞以填充。

例如:

int exec_uname(ssh_session session, int* bytes) {
  // ... code

  // Push back to caller
  *bytes = nbytes;
}

因此,當調用時:

int nbytes;
int result = exec_uname(session, &nbytes);
printf("Server output: %d", nbytes);

您仍然需要檢查result ,以確保函數正確終止,否則以nbytes為單位的值將不可用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM