AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / user-3938402

Harry's questions

Martin Hope
Harry
Asked: 2025-04-27 20:55:26 +0800 CST

在 shell 脚本终止时调用一个函数(清理处理程序)

  • 5

是否可以在shell脚本终止时调用一个函数?我有一些守护进程在后台运行,它们的进程ID存储在一个数组中。我希望在脚本终止时(无论出于何种原因)调用一个清理函数/处理程序来终止所有守护进程。

# want the below function to be called when the shell script terminates for whatsoever reason
purge () {
  for pid in ${pids[@]}; do
    kill -9 $pid
  done
}

./daemon1 > a.txt 2>&1 & pids+=($!)
./daemon2 > b.txt 2>&1 & pids+=($!)
./daemon3 > c.txt 2>&1 & pids+=($!)

for pid in ${pids[@]}; do
  echo "process: $pid"
done
linux
  • 1 个回答
  • 47 Views
Martin Hope
Harry
Asked: 2025-03-24 19:09:34 +0800 CST

根据 Ok 值将结果类型转换为另一种类型

  • 5

我如何才能根据值习惯性地将一种Result类型转换为另一种类型?ResultOk

fn get_res1() -> Result<bool, ()> {
    Ok(true)
}

fn get_res2() -> Result<(), String> {
    let res = get_res1().map_err(|err| String::from("Execution failed"))?;

    // map Ok value to Result type(function return type) based on its value
    // Is it possible to combine the below transformation with the above Result type method map_err?
    if !res {
        return Err(String::from("Operation failed"));
    }

    Ok(())
}
rust
  • 1 个回答
  • 58 Views
Martin Hope
Harry
Asked: 2025-02-25 15:14:17 +0800 CST

使用给定目录规范化包含当前目录的文件路径字符串

  • 6

是否可以将包含当前目录 ( .) 的文件路径字符串与给定目录进行规范化。例如,文件路径 => ./abcd.txt,给定目录 => /a/b/c。生成的文件路径的预期结果是/a/b/c/abcd.txt。

fn main() {
    let file_path = "./abcd.txt";
    let cur_dir = "/a/b/c";
    
    let path = std::fs::canonicalize(file_path).unwrap();
    println!("{:#?}", path);
}

输出

thread 'main' panicked at src/main.rs:5:49:
called `Result::unwrap()` on an `Err` value: Os { code: 2, kind: NotFound, message: "No such file or directory" }
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
rust
  • 1 个回答
  • 31 Views
Martin Hope
Harry
Asked: 2025-02-07 15:14:10 +0800 CST

匹配表达式末尾的分号[重复]

  • 6
这个问题已经有答案了:
为什么“临时变量是块末尾表达式的一部分”是错误? (1 个回答)
昨天休息。

在下面的代码中,如果我注释掉println!匹配表达式后的语句,就会出现借用检查器相关的问题。为了解决这个问题,编译器要求我在表达式末尾添加一个分号,match这解决了这个问题,但我不明白这样做的必要性。

use std::sync::{Arc, Mutex};

#[derive(Default)]
struct A {
    b: Arc<Mutex<B>>,
}

#[derive(Default)]
struct B {
    c: Arc<Mutex<C>>,
}

#[derive(Default)]
struct C {
    d: i32,
}

fn main() {
    let a = A::default();
    
    match a.b.lock().unwrap().c.lock().unwrap().d {
        0 => println!("zero"),
        _ => println!("non-zero"),
    }
    // uncommenting the below line makes borrow checker happy
    // println!("{}", a.b.lock().unwrap().c.lock().unwrap().d);
}

错误

error[E0597]: `a.b` does not live long enough
  --> src/main.rs:21:11
   |
19 |     let a = A::default();
   |         - binding `a` declared here
20 |     
21 |     match a.b.lock().unwrap().c.lock().unwrap().d {
   |           ^^^----------------
   |           |
   |           borrowed value does not live long enough
   |           a temporary with access to the borrow is created here ...
...
27 | }
   | -
   | |
   | `a.b` dropped here while still borrowed
   | ... and the borrow might be used here, when that temporary is dropped and runs the `Drop` code for type `MutexGuard`
   |
help: consider adding semicolon after the expression so its temporaries are dropped sooner, before the local variables declared by the block are dropped
   |
24 |     };
   |      +

For more information about this error, try `rustc --explain E0597`.
rust
  • 1 个回答
  • 50 Views
Martin Hope
Harry
Asked: 2025-01-14 12:49:59 +0800 CST

如何在编译时获取克隆的 git repo 的标签

  • 4

我已经克隆了一个远程 git repo 并从该main分支创建了一个新分支。现在我想在编译时获取最新的 repo 标签(如果存在)。我能够在编译时获取最新的提交哈希。以下是我的代码

// build.rs
use std::process::Command;
fn main() {
    let output = Command::new("git").args(&["rev-parse", "HEAD"]).output().unwrap();
    let git_hash = String::from_utf8(output.stdout).unwrap();
    println!("cargo:rustc-env=GIT_HASH={}", git_hash);
}

// main.rs
fn main() {
    println!("{}", env!("GIT_HASH"));
}
git
  • 2 个回答
  • 43 Views
Martin Hope
Harry
Asked: 2025-01-13 14:55:53 +0800 CST

如何使用 clap crate 打印版本和自定义命令行参数值

  • 5

我正在使用clapcrate 来处理命令行参数。如何同时打印版本号和自定义命令行参数?下面的代码运行时cargo run -- --name Harry --version仅打印版本号。

use clap::Parser;

/// Simple program to greet a person
#[derive(Parser, Debug)]
#[command(version, about, long_about = None)]
struct Args {
    /// Name of the person to greet
    #[arg(short, long)]
    name: String,

    /// Number of times to greet
    #[arg(short, long, default_value_t = 1)]
    count: u8,
}

fn main() {
    let args = Args::parse();

    for _ in 0..args.count {
        println!("Hello {}!", args.name);
    }
}

电流输出

clap_demo 0.1.0

预期输出

Hello Harry!
clap_demo 0.1.0

Cargo.toml

[package]
name = "clap_demo"
version = "0.1.0"
edition = "2021"

[dependencies]
clap = { version = "4.5.26", features = ["derive", "env"] }
rust
  • 1 个回答
  • 44 Views
Martin Hope
Harry
Asked: 2024-12-31 16:24:59 +0800 CST

如何传递一个闭包在 Ok 变量返回值之前执行

  • 5

我有一个返回Result类型的函数。在这个函数中,另一个返回类型的函数被调用Result。并且,如果返回的值是一个Err变体,则在冒泡该错误之前调用一个函数/闭包,否则,如果它是Ok变体,则调用一个函数/闭包,然后简单地返回所包含的值。这是我到目前为止写的内容

fn foo1() -> Result<i32, String> {
    Err("error".to_string())
}

fn foo2() -> Result<String, bool> {
    let res = foo1().map_err(|err| {
        println!("foo1 failed {}", err);
        false
    })?;

    // I know I can call some closure in here, but I want something like map_err which will call different closures depending on the Result variant
    Ok(res.to_string())
}

fn main() {
    foo2();
}
rust
  • 2 个回答
  • 62 Views
Martin Hope
Harry
Asked: 2024-12-18 13:40:11 +0800 CST

C++ std::filesystem 是否相当于 C stat 函数中的 st_blksize?

  • 7

是否有std::filesystem与 Cstat()函数等效的 C++ 函数#include <sys/stat.h>,用于获取有关该st_blksize属性的信息?

c++
  • 1 个回答
  • 64 Views
Martin Hope
Harry
Asked: 2024-12-13 14:58:50 +0800 CST

使用“$!”获取后台作业的 pid

  • 5

我编写了一个 shell 脚本来启动多个后台作业,并使用 将它们的进程 ID 存储在数组中$!。最后,我通过遍历数组打印所有进程 ID。我想知道编写的 shell 脚本是否有错误?而且,我觉得我的 shell 脚本中有错误的原因是,$!如果在我的 PC 中创建了多个进程,它可能会返回另一个进程的进程 ID。

#!/bin/bash

ps -a & pids+=($!) #Does $! return process id of command ps -a for sure
ls -la & pids+=($!) #Does $! return process id of command ls -la for sure
echo ${pids[0]}
echo ${pids[1]}
shell
  • 1 个回答
  • 21 Views
Martin Hope
Harry
Asked: 2024-12-04 17:48:38 +0800 CST

如何将双指针作为 const 双指针参数传递

  • 5

如何将非常量双指针作为常量参数传递给另一个函数?

我的代码:

#include <iostream>
    
void food(const char** begin, const char** end) {
    
}
    
int main(int argc, char** argv) {
    food(argv, argv + argc);    
}

我收到的错误:

<source>: In function 'int main(int, char**)':
<source>:8:10: error: invalid conversion from 'char**' to 'const char**' [-fpermissive]
    8 |     food(argv, argv + argc);
      |          ^~~~
      |          |
      |          char**
<source>:3:24: note:   initializing argument 1 of 'void food(const char**, const char**)'
    3 | void food(const char** begin, const char** end) {
      |           ~~~~~~~~~~~~~^~~~~
<source>:8:21: error: invalid conversion from 'char**' to 'const char**' [-fpermissive]
    8 |     food(argv, argv + argc);
      |                ~~~~~^~~~~~
      |                     |
      |                     char**
<source>:3:44: note:   initializing argument 2 of 'void food(const char**, const char**)'
    3 | void food(const char** begin, const char** end) {
      |      
c++
  • 3 个回答
  • 93 Views
Martin Hope
Harry
Asked: 2024-11-13 16:39:10 +0800 CST

使用空格作为包含 '-' 字符的分隔符来拆分字符串

  • 5

-我想使用空格作为分隔符来拆分包含第一个字符的字符串。但以下代码似乎不起作用。如果我删除该-字符,它就会正确拆分。这是脚本

#!/bin/bash

string="-e -/a/b/c/d"
arr=($string)
arrLen=${#arr[@]}
echo $arrLen
echo ${arr[0]} #prints empty
if [ $arrLen = 2 ] && [ ${arr[0]} = "-e" ]; then #this condition gets passed surprisingly
    echo "Hi ${arr[1]}"
fi

输出

2

Hi -a/b/c/d
bash
  • 1 个回答
  • 61 Views
Martin Hope
Harry
Asked: 2024-11-06 17:22:21 +0800 CST

使用 bash 脚本中的 here-document 命令创建文件[重复]

  • 6
此问题这里已有答案:
此处文档出现“文件意外结束”错误 (9 个答案)
15 小时前关闭。

如何使用cat带有此处文档的 shell 脚本命令来创建文件”

#!/bin/bash

create_file () {
    cat > a.txt << EOF
    0 abc def 
    ghi jkl mno
    pqrs tuv wxyz
    EOF
}

create_file

错误

Syntax error: end of file unexpected (expecting "}")
bash
  • 2 个回答
  • 53 Views
Martin Hope
Harry
Asked: 2024-06-10 15:49:47 +0800 CST

如何在数组指针类型参数上使用 std::bit_cast

  • 7

是否可以将数组第一个元素的地址作为参数传递给std::bit_cast.

#include <bit>
#include <iostream>

struct A {
    int a;
    int b;
    int c;
    int d;
    int e;

    void print() {
        std::cout << a << ", " << b << ", " << c << ", " << d << ", " << e << std::endl;
    }
};

int main() {
    char arr[20]{};
    // arr is filled with some data
    A a = std::bit_cast<A>(arr);
    a.print();

    const char* arrp = arr;
    // doesn't compile
    A b = std::bit_cast<A>(arrp);
    b.print();
}

错误

<source>: In function 'int main()':
<source>:23:27: error: no matching function for call to 'bit_cast<A>(const char*&)'
   23 |     A b = std::bit_cast<A>(arrp);
      |           ~~~~~~~~~~~~~~~~^~~~~~
In file included from <source>:1:
/opt/compiler-explorer/gcc-13.2.0/include/c++/13.2.0/bit:81:5: note: candidate: 'template<class _To, class _From> constexpr _To std::bit_cast(const _From&) requires  sizeof (_To) == sizeof (_From) && __is_trivially_copyable(_To) && __is_trivially_copyable(_From)'
   81 |     bit_cast(const _From& __from) noexcept
      |     ^~~~~~~~
/opt/compiler-explorer/gcc-13.2.0/include/c++/13.2.0/bit:81:5: note:   template argument deduction/substitution failed:
/opt/compiler-explorer/gcc-13.2.0/include/c++/13.2.0/bit:81:5: note: constraints not satisfied
/opt/compiler-explorer/gcc-13.2.0/include/c++/13.2.0/bit: In substitution of 'template<class _To, class _From> constexpr _To std::bit_cast(const _From&) requires  sizeof (_To) == sizeof (_From) && __is_trivially_copyable(_To) && __is_trivially_copyable(_From) [with _To = A; _From = const char*]':
<source>:23:27:   required from here
/opt/compiler-explorer/gcc-13.2.0/include/c++/13.2.0/bit:81:5:   required by the constraints of 'template<class _To, class _From> constexpr _To std::bit_cast(const _From&) requires  sizeof (_To) == sizeof (_From) && __is_trivially_copyable(_To) && __is_trivially_copyable(_From)'
/opt/compiler-explorer/gcc-13.2.0/include/c++/13.2.0/bit:83:27: note: the expression 'sizeof (_To) == sizeof (_From) [with _To = A; _From = const char*]' evaluated to 'false'
   83 |     requires (sizeof(_To) == sizeof(_From))
      |              ~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~
Compiler returned: 1
c++
  • 2 个回答
  • 71 Views
Martin Hope
Harry
Asked: 2024-05-29 13:13:28 +0800 CST

根据系统(本机)字节顺序重新解释缓冲区的字节

  • 6

我正在通过网络套接字以大端格式从另一台主机接收数据。如何解释以本机字节序格式接收的字节(例如获取视图或重新解释这些字节)而不复制到临时变量中。

#include <iostream>
#include <cstdint>

struct A {
    uint16_t msg_id;
    // contains many other fields where total size is greater than 4096

    void print() const {
        // print all the fields of struct A
    }
};

struct B {
    uint16_t msg_id;
    // contains many other fields where total size is greater than 4096

    void print() const {
        // print all the fields of struct B
    }
};

struct C {
    uint16_t msg_id;
    // contains many other fields where total size is greater than 4096

    void print() const {
        // print all the fields of struct C
    }
};

int main() {
    char buff[8192];
    while (true) {
        // data is received in network byte order (big endian) but my system is little endian
        const auto recvd_len = recvfrom(sock_fd, buff, sizeof(buff), 0, nullptr, nullptr);
        const uint16_t msg_id = (buff[0] << 8) | (buff[1] & 0xFF);

        switch (msg_id) {
            case 0x0001: {
                // reinterpret the bytes received as struct A, copy elision
                const A* a_obj = reinterpret_cast<const A*>(buff);
                a_obj->print();
                // the above print call works correctly only if my system is big endian but not little endian
            }

            break;

            case 0x0002: {
                // reinterpret the bytes received as struct B, copy elision
                const B* b_obj = reinterpret_cast<const B*>(buff);
                b_obj->print();
                // the above print call works correctly only if my system is big endian but not little endian
            }

            break;

            case 0x0003: {
                // reinterpret the bytes received as struct C, copy elision
                const C* c_obj = reinterpret_cast<const C*>(buff);
                c_obj->print();
                // the above print call works correctly only if my system is big endian but not little endian
            }

            break;

            default:
            break;
        }
    }
}
c++
  • 1 个回答
  • 81 Views
Martin Hope
Harry
Asked: 2024-05-21 20:17:11 +0800 CST

如何使用 std::uniform_int_distribution<>::operator()

  • 4

如何operator()(Generator& g, const param_type& params);使用std::uniform_int_distribution. 这是我的代码

#include <iostream>
#include <random>

int get_random_int(const int lower_limit, const int upper_limit) {
   std::random_device rd{};
   std::mt19937 gen{rd()};

   static std::uniform_int_distribution<> dist;
   
   // use operator()(Generator& g, const param_type& params);
   return dist(gen, lower_limit, upper_limit);
}

int main() {
    std::cout << get_random_int(1, 1000000) << std::endl;
}
c++
  • 2 个回答
  • 66 Views
Martin Hope
Harry
Asked: 2024-01-07 16:46:46 +0800 CST

如何对需要注释的元组使用“if let Ok()”语法

  • 5

我想知道是否可以对从crate https://docs.rs/bincode/2.0.0-rc.3/bincode/fn.decode_from_slice.html函数返回的类型使用if let Ok()语法,这需要显式类型注释Result<Tuple(Struct, usize), DecodeError>bincode::decode_from_slicebincode

我尝试了以下语法

struct A {
    a: i32,
    b: i32,
}

let mut recv_buff = [0u8; 1024];

if let Ok((a_obj, _): (A, usize)) = bincode::decode_from_slice(recv_buff, bincode::config::standard().with_big_endian()) {
        
}

错误

if let Ok((a_obj, _): (A, usize)) = bincode::decode_from_slice(recv_buff, bincode::config::standard()....
    |                                         ^ expected one of `)`, `,`, or `|`
rust
  • 2 个回答
  • 77 Views

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    重新格式化数字,在固定位置插入分隔符

    • 6 个回答
  • Marko Smith

    为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会?

    • 2 个回答
  • Marko Smith

    VScode 自动卸载扩展的问题(Material 主题)

    • 2 个回答
  • Marko Smith

    Vue 3:创建时出错“预期标识符但发现‘导入’”[重复]

    • 1 个回答
  • Marko Smith

    具有指定基础类型但没有枚举器的“枚举类”的用途是什么?

    • 1 个回答
  • Marko Smith

    如何修复未手动导入的模块的 MODULE_NOT_FOUND 错误?

    • 6 个回答
  • Marko Smith

    `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它?

    • 3 个回答
  • Marko Smith

    在 C++ 中,一个不执行任何操作的空程序需要 204KB 的堆,但在 C 中则不需要

    • 1 个回答
  • Marko Smith

    PowerBI 目前与 BigQuery 不兼容:Simba 驱动程序与 Windows 更新有关

    • 2 个回答
  • Marko Smith

    AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String”

    • 1 个回答
  • Martin Hope
    Fantastic Mr Fox msvc std::vector 实现中仅不接受可复制类型 2025-04-23 06:40:49 +0800 CST
  • Martin Hope
    Howard Hinnant 使用 chrono 查找下一个工作日 2025-04-21 08:30:25 +0800 CST
  • Martin Hope
    Fedor 构造函数的成员初始化程序可以包含另一个成员的初始化吗? 2025-04-15 01:01:44 +0800 CST
  • Martin Hope
    Petr Filipský 为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会? 2025-03-23 21:39:40 +0800 CST
  • Martin Hope
    Catskul C++20 是否进行了更改,允许从已知绑定数组“type(&)[N]”转换为未知绑定数组“type(&)[]”? 2025-03-04 06:57:53 +0800 CST
  • Martin Hope
    Stefan Pochmann 为什么 {2,3,10} 和 {x,3,10} (x=2) 的顺序不同? 2025-01-13 23:24:07 +0800 CST
  • Martin Hope
    Chad Feller 在 5.2 版中,bash 条件语句中的 [[ .. ]] 中的分号现在是可选的吗? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench 为什么双破折号 (--) 会导致此 MariaDB 子句评估为 true? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng 为什么 `dict(id=1, **{'id': 2})` 有时会引发 `KeyError: 'id'` 而不是 TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String” 2024-03-20 03:12:31 +0800 CST

热门标签

python javascript c++ c# java typescript sql reactjs html

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve