繁体   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